babylon.no-module.max.js 4.7 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070660716607266073660746607566076660776607866079660806608166082660836608466085660866608766088660896609066091660926609366094660956609666097660986609966100661016610266103661046610566106661076610866109661106611166112661136611466115661166611766118661196612066121661226612366124661256612666127661286612966130661316613266133661346613566136661376613866139661406614166142661436614466145661466614766148661496615066151661526615366154661556615666157661586615966160661616616266163661646616566166661676616866169661706617166172661736617466175661766617766178661796618066181661826618366184661856618666187661886618966190661916619266193661946619566196661976619866199662006620166202662036620466205662066620766208662096621066211662126621366214662156621666217662186621966220662216622266223662246622566226662276622866229662306623166232662336623466235662366623766238662396624066241662426624366244662456624666247662486624966250662516625266253662546625566256662576625866259662606626166262662636626466265662666626766268662696627066271662726627366274662756627666277662786627966280662816628266283662846628566286662876628866289662906629166292662936629466295662966629766298662996630066301663026630366304663056630666307663086630966310663116631266313663146631566316663176631866319663206632166322663236632466325663266632766328663296633066331663326633366334663356633666337663386633966340663416634266343663446634566346663476634866349663506635166352663536635466355663566635766358663596636066361663626636366364663656636666367663686636966370663716637266373663746637566376663776637866379663806638166382663836638466385663866638766388663896639066391663926639366394663956639666397663986639966400664016640266403664046640566406664076640866409664106641166412664136641466415664166641766418664196642066421664226642366424664256642666427664286642966430664316643266433664346643566436664376643866439664406644166442664436644466445664466644766448664496645066451664526645366454664556645666457664586645966460664616646266463664646646566466664676646866469664706647166472664736647466475664766647766478664796648066481664826648366484664856648666487664886648966490664916649266493664946649566496664976649866499665006650166502665036650466505665066650766508665096651066511665126651366514665156651666517665186651966520665216652266523665246652566526665276652866529665306653166532665336653466535665366653766538665396654066541665426654366544665456654666547665486654966550665516655266553665546655566556665576655866559665606656166562665636656466565665666656766568665696657066571665726657366574665756657666577665786657966580665816658266583665846658566586665876658866589665906659166592665936659466595665966659766598665996660066601666026660366604666056660666607666086660966610666116661266613666146661566616666176661866619666206662166622666236662466625666266662766628666296663066631666326663366634666356663666637666386663966640666416664266643666446664566646666476664866649666506665166652666536665466655666566665766658666596666066661666626666366664666656666666667666686666966670666716667266673666746667566676666776667866679666806668166682666836668466685666866668766688666896669066691666926669366694666956669666697666986669966700667016670266703667046670566706667076670866709667106671166712667136671466715667166671766718667196672066721667226672366724667256672666727667286672966730667316673266733667346673566736667376673866739667406674166742667436674466745667466674766748667496675066751667526675366754667556675666757667586675966760667616676266763667646676566766667676676866769667706677166772667736677466775667766677766778667796678066781667826678366784667856678666787667886678966790667916679266793667946679566796667976679866799668006680166802668036680466805668066680766808668096681066811668126681366814668156681666817668186681966820668216682266823668246682566826668276682866829668306683166832668336683466835668366683766838668396684066841668426684366844668456684666847668486684966850668516685266853668546685566856668576685866859668606686166862668636686466865668666686766868668696687066871668726687366874668756687666877668786687966880668816688266883668846688566886668876688866889668906689166892668936689466895668966689766898668996690066901669026690366904669056690666907669086690966910669116691266913669146691566916669176691866919669206692166922669236692466925669266692766928669296693066931669326693366934669356693666937669386693966940669416694266943669446694566946669476694866949669506695166952669536695466955669566695766958669596696066961669626696366964669656696666967669686696966970669716697266973669746697566976669776697866979669806698166982669836698466985669866698766988669896699066991669926699366994669956699666997669986699967000670016700267003670046700567006670076700867009670106701167012670136701467015670166701767018670196702067021670226702367024670256702667027670286702967030670316703267033670346703567036670376703867039670406704167042670436704467045670466704767048670496705067051670526705367054670556705667057670586705967060670616706267063670646706567066670676706867069670706707167072670736707467075670766707767078670796708067081670826708367084670856708667087670886708967090670916709267093670946709567096670976709867099671006710167102671036710467105671066710767108671096711067111671126711367114671156711667117671186711967120671216712267123671246712567126671276712867129671306713167132671336713467135671366713767138671396714067141671426714367144671456714667147671486714967150671516715267153671546715567156671576715867159671606716167162671636716467165671666716767168671696717067171671726717367174671756717667177671786717967180671816718267183671846718567186671876718867189671906719167192671936719467195671966719767198671996720067201672026720367204672056720667207672086720967210672116721267213672146721567216672176721867219672206722167222672236722467225672266722767228672296723067231672326723367234672356723667237672386723967240672416724267243672446724567246672476724867249672506725167252672536725467255672566725767258672596726067261672626726367264672656726667267672686726967270672716727267273672746727567276672776727867279672806728167282672836728467285672866728767288672896729067291672926729367294672956729667297672986729967300673016730267303673046730567306673076730867309673106731167312673136731467315673166731767318673196732067321673226732367324673256732667327673286732967330673316733267333673346733567336673376733867339673406734167342673436734467345673466734767348673496735067351673526735367354673556735667357673586735967360673616736267363673646736567366673676736867369673706737167372673736737467375673766737767378673796738067381673826738367384673856738667387673886738967390673916739267393673946739567396673976739867399674006740167402674036740467405674066740767408674096741067411674126741367414674156741667417674186741967420674216742267423674246742567426674276742867429674306743167432674336743467435674366743767438674396744067441674426744367444674456744667447674486744967450674516745267453674546745567456674576745867459674606746167462674636746467465674666746767468674696747067471674726747367474674756747667477674786747967480674816748267483674846748567486674876748867489674906749167492674936749467495674966749767498674996750067501675026750367504675056750667507675086750967510675116751267513675146751567516675176751867519675206752167522675236752467525675266752767528675296753067531675326753367534675356753667537675386753967540675416754267543675446754567546675476754867549675506755167552675536755467555675566755767558675596756067561675626756367564675656756667567675686756967570675716757267573675746757567576675776757867579675806758167582675836758467585675866758767588675896759067591675926759367594675956759667597675986759967600676016760267603676046760567606676076760867609676106761167612676136761467615676166761767618676196762067621676226762367624676256762667627676286762967630676316763267633676346763567636676376763867639676406764167642676436764467645676466764767648676496765067651676526765367654676556765667657676586765967660676616766267663676646766567666676676766867669676706767167672676736767467675676766767767678676796768067681676826768367684676856768667687676886768967690676916769267693676946769567696676976769867699677006770167702677036770467705677066770767708677096771067711677126771367714677156771667717677186771967720677216772267723677246772567726677276772867729677306773167732677336773467735677366773767738677396774067741677426774367744677456774667747677486774967750677516775267753677546775567756677576775867759677606776167762677636776467765677666776767768677696777067771677726777367774677756777667777677786777967780677816778267783677846778567786677876778867789677906779167792677936779467795677966779767798677996780067801678026780367804678056780667807678086780967810678116781267813678146781567816678176781867819678206782167822678236782467825678266782767828678296783067831678326783367834678356783667837678386783967840678416784267843678446784567846678476784867849678506785167852678536785467855678566785767858678596786067861678626786367864678656786667867678686786967870678716787267873678746787567876678776787867879678806788167882678836788467885678866788767888678896789067891678926789367894678956789667897678986789967900679016790267903679046790567906679076790867909679106791167912679136791467915679166791767918679196792067921679226792367924679256792667927679286792967930679316793267933679346793567936679376793867939679406794167942679436794467945679466794767948679496795067951679526795367954679556795667957679586795967960679616796267963679646796567966679676796867969679706797167972679736797467975679766797767978679796798067981679826798367984679856798667987679886798967990679916799267993679946799567996679976799867999680006800168002680036800468005680066800768008680096801068011680126801368014680156801668017680186801968020680216802268023680246802568026680276802868029680306803168032680336803468035680366803768038680396804068041680426804368044680456804668047680486804968050680516805268053680546805568056680576805868059680606806168062680636806468065680666806768068680696807068071680726807368074680756807668077680786807968080680816808268083680846808568086680876808868089680906809168092680936809468095680966809768098680996810068101681026810368104681056810668107681086810968110681116811268113681146811568116681176811868119681206812168122681236812468125681266812768128681296813068131681326813368134681356813668137681386813968140681416814268143681446814568146681476814868149681506815168152681536815468155681566815768158681596816068161681626816368164681656816668167681686816968170681716817268173681746817568176681776817868179681806818168182681836818468185681866818768188681896819068191681926819368194681956819668197681986819968200682016820268203682046820568206682076820868209682106821168212682136821468215682166821768218682196822068221682226822368224682256822668227682286822968230682316823268233682346823568236682376823868239682406824168242682436824468245682466824768248682496825068251682526825368254682556825668257682586825968260682616826268263682646826568266682676826868269682706827168272682736827468275682766827768278682796828068281682826828368284682856828668287682886828968290682916829268293682946829568296682976829868299683006830168302683036830468305683066830768308683096831068311683126831368314683156831668317683186831968320683216832268323683246832568326683276832868329683306833168332683336833468335683366833768338683396834068341683426834368344683456834668347683486834968350683516835268353683546835568356683576835868359683606836168362683636836468365683666836768368683696837068371683726837368374683756837668377683786837968380683816838268383683846838568386683876838868389683906839168392683936839468395683966839768398683996840068401684026840368404684056840668407684086840968410684116841268413684146841568416684176841868419684206842168422684236842468425684266842768428684296843068431684326843368434684356843668437684386843968440684416844268443684446844568446684476844868449684506845168452684536845468455684566845768458684596846068461684626846368464684656846668467684686846968470684716847268473684746847568476684776847868479684806848168482684836848468485684866848768488684896849068491684926849368494684956849668497684986849968500685016850268503685046850568506685076850868509685106851168512685136851468515685166851768518685196852068521685226852368524685256852668527685286852968530685316853268533685346853568536685376853868539685406854168542685436854468545685466854768548685496855068551685526855368554685556855668557685586855968560685616856268563685646856568566685676856868569685706857168572685736857468575685766857768578685796858068581685826858368584685856858668587685886858968590685916859268593685946859568596685976859868599686006860168602686036860468605686066860768608686096861068611686126861368614686156861668617686186861968620686216862268623686246862568626686276862868629686306863168632686336863468635686366863768638686396864068641686426864368644686456864668647686486864968650686516865268653686546865568656686576865868659686606866168662686636866468665686666866768668686696867068671686726867368674686756867668677686786867968680686816868268683686846868568686686876868868689686906869168692686936869468695686966869768698686996870068701687026870368704687056870668707687086870968710687116871268713687146871568716687176871868719687206872168722687236872468725687266872768728687296873068731687326873368734687356873668737687386873968740687416874268743687446874568746687476874868749687506875168752687536875468755687566875768758687596876068761687626876368764687656876668767687686876968770687716877268773687746877568776687776877868779687806878168782687836878468785687866878768788687896879068791687926879368794687956879668797687986879968800688016880268803688046880568806688076880868809688106881168812688136881468815688166881768818688196882068821688226882368824688256882668827688286882968830688316883268833688346883568836688376883868839688406884168842688436884468845688466884768848688496885068851688526885368854688556885668857688586885968860688616886268863688646886568866688676886868869688706887168872688736887468875688766887768878688796888068881688826888368884688856888668887688886888968890688916889268893688946889568896688976889868899689006890168902689036890468905689066890768908689096891068911689126891368914689156891668917689186891968920689216892268923689246892568926689276892868929689306893168932689336893468935689366893768938689396894068941689426894368944689456894668947689486894968950689516895268953689546895568956689576895868959689606896168962689636896468965689666896768968689696897068971689726897368974689756897668977689786897968980689816898268983689846898568986689876898868989689906899168992689936899468995689966899768998689996900069001690026900369004690056900669007690086900969010690116901269013690146901569016690176901869019690206902169022690236902469025690266902769028690296903069031690326903369034690356903669037690386903969040690416904269043690446904569046690476904869049690506905169052690536905469055690566905769058690596906069061690626906369064690656906669067690686906969070690716907269073690746907569076690776907869079690806908169082690836908469085690866908769088690896909069091690926909369094690956909669097690986909969100691016910269103691046910569106691076910869109691106911169112691136911469115691166911769118691196912069121691226912369124691256912669127691286912969130691316913269133691346913569136691376913869139691406914169142691436914469145691466914769148691496915069151691526915369154691556915669157691586915969160691616916269163691646916569166691676916869169691706917169172691736917469175691766917769178691796918069181691826918369184691856918669187691886918969190691916919269193691946919569196691976919869199692006920169202692036920469205692066920769208692096921069211692126921369214692156921669217692186921969220692216922269223692246922569226692276922869229692306923169232692336923469235692366923769238692396924069241692426924369244692456924669247692486924969250692516925269253692546925569256692576925869259692606926169262692636926469265692666926769268692696927069271692726927369274692756927669277692786927969280692816928269283692846928569286692876928869289692906929169292692936929469295692966929769298692996930069301693026930369304693056930669307693086930969310693116931269313693146931569316693176931869319693206932169322693236932469325693266932769328693296933069331693326933369334693356933669337693386933969340693416934269343693446934569346693476934869349693506935169352693536935469355693566935769358693596936069361693626936369364693656936669367693686936969370693716937269373693746937569376693776937869379693806938169382693836938469385693866938769388693896939069391693926939369394693956939669397693986939969400694016940269403694046940569406694076940869409694106941169412694136941469415694166941769418694196942069421694226942369424694256942669427694286942969430694316943269433694346943569436694376943869439694406944169442694436944469445694466944769448694496945069451694526945369454694556945669457694586945969460694616946269463694646946569466694676946869469694706947169472694736947469475694766947769478694796948069481694826948369484694856948669487694886948969490694916949269493694946949569496694976949869499695006950169502695036950469505695066950769508695096951069511695126951369514695156951669517695186951969520695216952269523695246952569526695276952869529695306953169532695336953469535695366953769538695396954069541695426954369544695456954669547695486954969550695516955269553695546955569556695576955869559695606956169562695636956469565695666956769568695696957069571695726957369574695756957669577695786957969580695816958269583695846958569586695876958869589695906959169592695936959469595695966959769598695996960069601696026960369604696056960669607696086960969610696116961269613696146961569616696176961869619696206962169622696236962469625696266962769628696296963069631696326963369634696356963669637696386963969640696416964269643696446964569646696476964869649696506965169652696536965469655696566965769658696596966069661696626966369664696656966669667696686966969670696716967269673696746967569676696776967869679696806968169682696836968469685696866968769688696896969069691696926969369694696956969669697696986969969700697016970269703697046970569706697076970869709697106971169712697136971469715697166971769718697196972069721697226972369724697256972669727697286972969730697316973269733697346973569736697376973869739697406974169742697436974469745697466974769748697496975069751697526975369754697556975669757697586975969760697616976269763697646976569766697676976869769697706977169772697736977469775697766977769778697796978069781697826978369784697856978669787697886978969790697916979269793697946979569796697976979869799698006980169802698036980469805698066980769808698096981069811698126981369814698156981669817698186981969820698216982269823698246982569826698276982869829698306983169832698336983469835698366983769838698396984069841698426984369844698456984669847698486984969850698516985269853698546985569856698576985869859698606986169862698636986469865698666986769868698696987069871698726987369874698756987669877698786987969880698816988269883698846988569886698876988869889698906989169892698936989469895698966989769898698996990069901699026990369904699056990669907699086990969910699116991269913699146991569916699176991869919699206992169922699236992469925699266992769928699296993069931699326993369934699356993669937699386993969940699416994269943699446994569946699476994869949699506995169952699536995469955699566995769958699596996069961699626996369964699656996669967699686996969970699716997269973699746997569976699776997869979699806998169982699836998469985699866998769988699896999069991699926999369994699956999669997699986999970000700017000270003700047000570006700077000870009700107001170012700137001470015700167001770018700197002070021700227002370024700257002670027700287002970030700317003270033700347003570036700377003870039700407004170042700437004470045700467004770048700497005070051700527005370054700557005670057700587005970060700617006270063700647006570066700677006870069700707007170072700737007470075700767007770078700797008070081700827008370084700857008670087700887008970090700917009270093700947009570096700977009870099701007010170102701037010470105701067010770108701097011070111701127011370114701157011670117701187011970120701217012270123701247012570126701277012870129701307013170132701337013470135701367013770138701397014070141701427014370144701457014670147701487014970150701517015270153701547015570156701577015870159701607016170162701637016470165701667016770168701697017070171701727017370174701757017670177701787017970180701817018270183701847018570186701877018870189701907019170192701937019470195701967019770198701997020070201702027020370204702057020670207702087020970210702117021270213702147021570216702177021870219702207022170222702237022470225702267022770228702297023070231702327023370234702357023670237702387023970240702417024270243702447024570246702477024870249702507025170252702537025470255702567025770258702597026070261702627026370264702657026670267702687026970270702717027270273702747027570276702777027870279702807028170282702837028470285702867028770288702897029070291702927029370294702957029670297702987029970300703017030270303703047030570306703077030870309703107031170312703137031470315703167031770318703197032070321703227032370324703257032670327703287032970330703317033270333703347033570336703377033870339703407034170342703437034470345703467034770348703497035070351703527035370354703557035670357703587035970360703617036270363703647036570366703677036870369703707037170372703737037470375703767037770378703797038070381703827038370384703857038670387703887038970390703917039270393703947039570396703977039870399704007040170402704037040470405704067040770408704097041070411704127041370414704157041670417704187041970420704217042270423704247042570426704277042870429704307043170432704337043470435704367043770438704397044070441704427044370444704457044670447704487044970450704517045270453704547045570456704577045870459704607046170462704637046470465704667046770468704697047070471704727047370474704757047670477704787047970480704817048270483704847048570486704877048870489704907049170492704937049470495704967049770498704997050070501705027050370504705057050670507705087050970510705117051270513705147051570516705177051870519705207052170522705237052470525705267052770528705297053070531705327053370534705357053670537705387053970540705417054270543705447054570546705477054870549705507055170552705537055470555705567055770558705597056070561705627056370564705657056670567705687056970570705717057270573705747057570576705777057870579705807058170582705837058470585705867058770588705897059070591705927059370594705957059670597705987059970600706017060270603706047060570606706077060870609706107061170612706137061470615706167061770618706197062070621706227062370624706257062670627706287062970630706317063270633706347063570636706377063870639706407064170642706437064470645706467064770648706497065070651706527065370654706557065670657706587065970660706617066270663706647066570666706677066870669706707067170672706737067470675706767067770678706797068070681706827068370684706857068670687706887068970690706917069270693706947069570696706977069870699707007070170702707037070470705707067070770708707097071070711707127071370714707157071670717707187071970720707217072270723707247072570726707277072870729707307073170732707337073470735707367073770738707397074070741707427074370744707457074670747707487074970750707517075270753707547075570756707577075870759707607076170762707637076470765707667076770768707697077070771707727077370774707757077670777707787077970780707817078270783707847078570786707877078870789707907079170792707937079470795707967079770798707997080070801708027080370804708057080670807708087080970810708117081270813708147081570816708177081870819708207082170822708237082470825708267082770828708297083070831708327083370834708357083670837708387083970840708417084270843708447084570846708477084870849708507085170852708537085470855708567085770858708597086070861708627086370864708657086670867708687086970870708717087270873708747087570876708777087870879708807088170882708837088470885708867088770888708897089070891708927089370894708957089670897708987089970900709017090270903709047090570906709077090870909709107091170912709137091470915709167091770918709197092070921709227092370924709257092670927709287092970930709317093270933709347093570936709377093870939709407094170942709437094470945709467094770948709497095070951709527095370954709557095670957709587095970960709617096270963709647096570966709677096870969709707097170972709737097470975709767097770978709797098070981709827098370984709857098670987709887098970990709917099270993709947099570996709977099870999710007100171002710037100471005710067100771008710097101071011710127101371014710157101671017710187101971020710217102271023710247102571026710277102871029710307103171032710337103471035710367103771038710397104071041710427104371044710457104671047710487104971050710517105271053710547105571056710577105871059710607106171062710637106471065710667106771068710697107071071710727107371074710757107671077710787107971080710817108271083710847108571086710877108871089710907109171092710937109471095710967109771098710997110071101711027110371104711057110671107711087110971110711117111271113711147111571116711177111871119711207112171122711237112471125711267112771128711297113071131711327113371134711357113671137711387113971140711417114271143711447114571146711477114871149711507115171152711537115471155711567115771158711597116071161711627116371164711657116671167711687116971170711717117271173711747117571176711777117871179711807118171182711837118471185711867118771188711897119071191711927119371194711957119671197711987119971200712017120271203712047120571206712077120871209712107121171212712137121471215712167121771218712197122071221712227122371224712257122671227712287122971230712317123271233712347123571236712377123871239712407124171242712437124471245712467124771248712497125071251712527125371254712557125671257712587125971260712617126271263712647126571266712677126871269712707127171272712737127471275712767127771278712797128071281712827128371284712857128671287712887128971290712917129271293712947129571296712977129871299713007130171302713037130471305713067130771308713097131071311713127131371314713157131671317713187131971320713217132271323713247132571326713277132871329713307133171332713337133471335713367133771338713397134071341713427134371344713457134671347713487134971350713517135271353713547135571356713577135871359713607136171362713637136471365713667136771368713697137071371713727137371374713757137671377713787137971380713817138271383713847138571386713877138871389713907139171392713937139471395713967139771398713997140071401714027140371404714057140671407714087140971410714117141271413714147141571416714177141871419714207142171422714237142471425714267142771428714297143071431714327143371434714357143671437714387143971440714417144271443714447144571446714477144871449714507145171452714537145471455714567145771458714597146071461714627146371464714657146671467714687146971470714717147271473714747147571476714777147871479714807148171482714837148471485714867148771488714897149071491714927149371494714957149671497714987149971500715017150271503715047150571506715077150871509715107151171512715137151471515715167151771518715197152071521715227152371524715257152671527715287152971530715317153271533715347153571536715377153871539715407154171542715437154471545715467154771548715497155071551715527155371554715557155671557715587155971560715617156271563715647156571566715677156871569715707157171572715737157471575715767157771578715797158071581715827158371584715857158671587715887158971590715917159271593715947159571596715977159871599716007160171602716037160471605716067160771608716097161071611716127161371614716157161671617716187161971620716217162271623716247162571626716277162871629716307163171632716337163471635716367163771638716397164071641716427164371644716457164671647716487164971650716517165271653716547165571656716577165871659716607166171662716637166471665716667166771668716697167071671716727167371674716757167671677716787167971680716817168271683716847168571686716877168871689716907169171692716937169471695716967169771698716997170071701717027170371704717057170671707717087170971710717117171271713717147171571716717177171871719717207172171722717237172471725717267172771728717297173071731717327173371734717357173671737717387173971740717417174271743717447174571746717477174871749717507175171752717537175471755717567175771758717597176071761717627176371764717657176671767717687176971770717717177271773717747177571776717777177871779717807178171782717837178471785717867178771788717897179071791717927179371794717957179671797717987179971800718017180271803718047180571806718077180871809718107181171812718137181471815718167181771818718197182071821718227182371824718257182671827718287182971830718317183271833718347183571836718377183871839718407184171842718437184471845718467184771848718497185071851718527185371854718557185671857718587185971860718617186271863718647186571866718677186871869718707187171872718737187471875718767187771878718797188071881718827188371884718857188671887718887188971890718917189271893718947189571896718977189871899719007190171902719037190471905719067190771908719097191071911719127191371914719157191671917719187191971920719217192271923719247192571926719277192871929719307193171932719337193471935719367193771938719397194071941719427194371944719457194671947719487194971950719517195271953719547195571956719577195871959719607196171962719637196471965719667196771968719697197071971719727197371974719757197671977719787197971980719817198271983719847198571986719877198871989719907199171992719937199471995719967199771998719997200072001720027200372004720057200672007720087200972010720117201272013720147201572016720177201872019720207202172022720237202472025720267202772028720297203072031720327203372034720357203672037720387203972040720417204272043720447204572046720477204872049720507205172052720537205472055720567205772058720597206072061720627206372064720657206672067720687206972070720717207272073720747207572076720777207872079720807208172082720837208472085720867208772088720897209072091720927209372094720957209672097720987209972100721017210272103721047210572106721077210872109721107211172112721137211472115721167211772118721197212072121721227212372124721257212672127721287212972130721317213272133721347213572136721377213872139721407214172142721437214472145721467214772148721497215072151721527215372154721557215672157721587215972160721617216272163721647216572166721677216872169721707217172172721737217472175721767217772178721797218072181721827218372184721857218672187721887218972190721917219272193721947219572196721977219872199722007220172202722037220472205722067220772208722097221072211722127221372214722157221672217722187221972220722217222272223722247222572226722277222872229722307223172232722337223472235722367223772238722397224072241722427224372244722457224672247722487224972250722517225272253722547225572256722577225872259722607226172262722637226472265722667226772268722697227072271722727227372274722757227672277722787227972280722817228272283722847228572286722877228872289722907229172292722937229472295722967229772298722997230072301723027230372304723057230672307723087230972310723117231272313723147231572316723177231872319723207232172322723237232472325723267232772328723297233072331723327233372334723357233672337723387233972340723417234272343723447234572346723477234872349723507235172352723537235472355723567235772358723597236072361723627236372364723657236672367723687236972370723717237272373723747237572376723777237872379723807238172382723837238472385723867238772388723897239072391723927239372394723957239672397723987239972400724017240272403724047240572406724077240872409724107241172412724137241472415724167241772418724197242072421724227242372424724257242672427724287242972430724317243272433724347243572436724377243872439724407244172442724437244472445724467244772448724497245072451724527245372454724557245672457724587245972460724617246272463724647246572466724677246872469724707247172472724737247472475724767247772478724797248072481724827248372484724857248672487724887248972490724917249272493724947249572496724977249872499725007250172502725037250472505725067250772508725097251072511725127251372514725157251672517725187251972520725217252272523725247252572526725277252872529725307253172532725337253472535725367253772538725397254072541725427254372544725457254672547725487254972550725517255272553725547255572556725577255872559725607256172562725637256472565725667256772568725697257072571725727257372574725757257672577725787257972580725817258272583725847258572586725877258872589725907259172592725937259472595725967259772598725997260072601726027260372604726057260672607726087260972610726117261272613726147261572616726177261872619726207262172622726237262472625726267262772628726297263072631726327263372634726357263672637726387263972640726417264272643726447264572646726477264872649726507265172652726537265472655726567265772658726597266072661726627266372664726657266672667726687266972670726717267272673726747267572676726777267872679726807268172682726837268472685726867268772688726897269072691726927269372694726957269672697726987269972700727017270272703727047270572706727077270872709727107271172712727137271472715727167271772718727197272072721727227272372724727257272672727727287272972730727317273272733727347273572736727377273872739727407274172742727437274472745727467274772748727497275072751727527275372754727557275672757727587275972760727617276272763727647276572766727677276872769727707277172772727737277472775727767277772778727797278072781727827278372784727857278672787727887278972790727917279272793727947279572796727977279872799728007280172802728037280472805728067280772808728097281072811728127281372814728157281672817728187281972820728217282272823728247282572826728277282872829728307283172832728337283472835728367283772838728397284072841728427284372844728457284672847728487284972850728517285272853728547285572856728577285872859728607286172862728637286472865728667286772868728697287072871728727287372874728757287672877728787287972880728817288272883728847288572886728877288872889728907289172892728937289472895728967289772898728997290072901729027290372904729057290672907729087290972910729117291272913729147291572916729177291872919729207292172922729237292472925729267292772928729297293072931729327293372934729357293672937729387293972940729417294272943729447294572946729477294872949729507295172952729537295472955729567295772958729597296072961729627296372964729657296672967729687296972970729717297272973729747297572976729777297872979729807298172982729837298472985729867298772988729897299072991729927299372994729957299672997729987299973000730017300273003730047300573006730077300873009730107301173012730137301473015730167301773018730197302073021730227302373024730257302673027730287302973030730317303273033730347303573036730377303873039730407304173042730437304473045730467304773048730497305073051730527305373054730557305673057730587305973060730617306273063730647306573066730677306873069730707307173072730737307473075730767307773078730797308073081730827308373084730857308673087730887308973090730917309273093730947309573096730977309873099731007310173102731037310473105731067310773108731097311073111731127311373114731157311673117731187311973120731217312273123731247312573126731277312873129731307313173132731337313473135731367313773138731397314073141731427314373144731457314673147731487314973150731517315273153731547315573156731577315873159731607316173162731637316473165731667316773168731697317073171731727317373174731757317673177731787317973180731817318273183731847318573186731877318873189731907319173192731937319473195731967319773198731997320073201732027320373204732057320673207732087320973210732117321273213732147321573216732177321873219732207322173222732237322473225732267322773228732297323073231732327323373234732357323673237732387323973240732417324273243732447324573246732477324873249732507325173252732537325473255732567325773258732597326073261732627326373264732657326673267732687326973270732717327273273732747327573276732777327873279732807328173282732837328473285732867328773288732897329073291732927329373294732957329673297732987329973300733017330273303733047330573306733077330873309733107331173312733137331473315733167331773318733197332073321733227332373324733257332673327733287332973330733317333273333733347333573336733377333873339733407334173342733437334473345733467334773348733497335073351733527335373354733557335673357733587335973360733617336273363733647336573366733677336873369733707337173372733737337473375733767337773378733797338073381733827338373384733857338673387733887338973390733917339273393733947339573396733977339873399734007340173402734037340473405734067340773408734097341073411734127341373414734157341673417734187341973420734217342273423734247342573426734277342873429734307343173432734337343473435734367343773438734397344073441734427344373444734457344673447734487344973450734517345273453734547345573456734577345873459734607346173462734637346473465734667346773468734697347073471734727347373474734757347673477734787347973480734817348273483734847348573486734877348873489734907349173492734937349473495734967349773498734997350073501735027350373504735057350673507735087350973510735117351273513735147351573516735177351873519735207352173522735237352473525735267352773528735297353073531735327353373534735357353673537735387353973540735417354273543735447354573546735477354873549735507355173552735537355473555735567355773558735597356073561735627356373564735657356673567735687356973570735717357273573735747357573576735777357873579735807358173582735837358473585735867358773588735897359073591735927359373594735957359673597735987359973600736017360273603736047360573606736077360873609736107361173612736137361473615736167361773618736197362073621736227362373624736257362673627736287362973630736317363273633736347363573636736377363873639736407364173642736437364473645736467364773648736497365073651736527365373654736557365673657736587365973660736617366273663736647366573666736677366873669736707367173672736737367473675736767367773678736797368073681736827368373684736857368673687736887368973690736917369273693736947369573696736977369873699737007370173702737037370473705737067370773708737097371073711737127371373714737157371673717737187371973720737217372273723737247372573726737277372873729737307373173732737337373473735737367373773738737397374073741737427374373744737457374673747737487374973750737517375273753737547375573756737577375873759737607376173762737637376473765737667376773768737697377073771737727377373774737757377673777737787377973780737817378273783737847378573786737877378873789737907379173792737937379473795737967379773798737997380073801738027380373804738057380673807738087380973810738117381273813738147381573816738177381873819738207382173822738237382473825738267382773828738297383073831738327383373834738357383673837738387383973840738417384273843738447384573846738477384873849738507385173852738537385473855738567385773858738597386073861738627386373864738657386673867738687386973870738717387273873738747387573876738777387873879738807388173882738837388473885738867388773888738897389073891738927389373894738957389673897738987389973900739017390273903739047390573906739077390873909739107391173912739137391473915739167391773918739197392073921739227392373924739257392673927739287392973930739317393273933739347393573936739377393873939739407394173942739437394473945739467394773948739497395073951739527395373954739557395673957739587395973960739617396273963739647396573966739677396873969739707397173972739737397473975739767397773978739797398073981739827398373984739857398673987739887398973990739917399273993739947399573996739977399873999740007400174002740037400474005740067400774008740097401074011740127401374014740157401674017740187401974020740217402274023740247402574026740277402874029740307403174032740337403474035740367403774038740397404074041740427404374044740457404674047740487404974050740517405274053740547405574056740577405874059740607406174062740637406474065740667406774068740697407074071740727407374074740757407674077740787407974080740817408274083740847408574086740877408874089740907409174092740937409474095740967409774098740997410074101741027410374104741057410674107741087410974110741117411274113741147411574116741177411874119741207412174122741237412474125741267412774128741297413074131741327413374134741357413674137741387413974140741417414274143741447414574146741477414874149741507415174152741537415474155741567415774158741597416074161741627416374164741657416674167741687416974170741717417274173741747417574176741777417874179741807418174182741837418474185741867418774188741897419074191741927419374194741957419674197741987419974200742017420274203742047420574206742077420874209742107421174212742137421474215742167421774218742197422074221742227422374224742257422674227742287422974230742317423274233742347423574236742377423874239742407424174242742437424474245742467424774248742497425074251742527425374254742557425674257742587425974260742617426274263742647426574266742677426874269742707427174272742737427474275742767427774278742797428074281742827428374284742857428674287742887428974290742917429274293742947429574296742977429874299743007430174302743037430474305743067430774308743097431074311743127431374314743157431674317743187431974320743217432274323743247432574326743277432874329743307433174332743337433474335743367433774338743397434074341743427434374344743457434674347743487434974350743517435274353743547435574356743577435874359743607436174362743637436474365743667436774368743697437074371743727437374374743757437674377743787437974380743817438274383743847438574386743877438874389743907439174392743937439474395743967439774398743997440074401744027440374404744057440674407744087440974410744117441274413744147441574416744177441874419744207442174422744237442474425744267442774428744297443074431744327443374434744357443674437744387443974440744417444274443744447444574446744477444874449744507445174452744537445474455744567445774458744597446074461744627446374464744657446674467744687446974470744717447274473744747447574476744777447874479744807448174482744837448474485744867448774488744897449074491744927449374494744957449674497744987449974500745017450274503745047450574506745077450874509745107451174512745137451474515745167451774518745197452074521745227452374524745257452674527745287452974530745317453274533745347453574536745377453874539745407454174542745437454474545745467454774548745497455074551745527455374554745557455674557745587455974560745617456274563745647456574566745677456874569745707457174572745737457474575745767457774578745797458074581745827458374584745857458674587745887458974590745917459274593745947459574596745977459874599746007460174602746037460474605746067460774608746097461074611746127461374614746157461674617746187461974620746217462274623746247462574626746277462874629746307463174632746337463474635746367463774638746397464074641746427464374644746457464674647746487464974650746517465274653746547465574656746577465874659746607466174662746637466474665746667466774668746697467074671746727467374674746757467674677746787467974680746817468274683746847468574686746877468874689746907469174692746937469474695746967469774698746997470074701747027470374704747057470674707747087470974710747117471274713747147471574716747177471874719747207472174722747237472474725747267472774728747297473074731747327473374734747357473674737747387473974740747417474274743747447474574746747477474874749747507475174752747537475474755747567475774758747597476074761747627476374764747657476674767747687476974770747717477274773747747477574776747777477874779747807478174782747837478474785747867478774788747897479074791747927479374794747957479674797747987479974800748017480274803748047480574806748077480874809748107481174812748137481474815748167481774818748197482074821748227482374824748257482674827748287482974830748317483274833748347483574836748377483874839748407484174842748437484474845748467484774848748497485074851748527485374854748557485674857748587485974860748617486274863748647486574866748677486874869748707487174872748737487474875748767487774878748797488074881748827488374884748857488674887748887488974890748917489274893748947489574896748977489874899749007490174902749037490474905749067490774908749097491074911749127491374914749157491674917749187491974920749217492274923749247492574926749277492874929749307493174932749337493474935749367493774938749397494074941749427494374944749457494674947749487494974950749517495274953749547495574956749577495874959749607496174962749637496474965749667496774968749697497074971749727497374974749757497674977749787497974980749817498274983749847498574986749877498874989749907499174992749937499474995749967499774998749997500075001750027500375004750057500675007750087500975010750117501275013750147501575016750177501875019750207502175022750237502475025750267502775028750297503075031750327503375034750357503675037750387503975040750417504275043750447504575046750477504875049750507505175052750537505475055750567505775058750597506075061750627506375064750657506675067750687506975070750717507275073750747507575076750777507875079750807508175082750837508475085750867508775088750897509075091750927509375094750957509675097750987509975100751017510275103751047510575106751077510875109751107511175112751137511475115751167511775118751197512075121751227512375124751257512675127751287512975130751317513275133751347513575136751377513875139751407514175142751437514475145751467514775148751497515075151751527515375154751557515675157751587515975160751617516275163751647516575166751677516875169751707517175172751737517475175751767517775178751797518075181751827518375184751857518675187751887518975190751917519275193751947519575196751977519875199752007520175202752037520475205752067520775208752097521075211752127521375214752157521675217752187521975220752217522275223752247522575226752277522875229752307523175232752337523475235752367523775238752397524075241752427524375244752457524675247752487524975250752517525275253752547525575256752577525875259752607526175262752637526475265752667526775268752697527075271752727527375274752757527675277752787527975280752817528275283752847528575286752877528875289752907529175292752937529475295752967529775298752997530075301753027530375304753057530675307753087530975310753117531275313753147531575316753177531875319753207532175322753237532475325753267532775328753297533075331753327533375334753357533675337753387533975340753417534275343753447534575346753477534875349753507535175352753537535475355753567535775358753597536075361753627536375364753657536675367753687536975370753717537275373753747537575376753777537875379753807538175382753837538475385753867538775388753897539075391753927539375394753957539675397753987539975400754017540275403754047540575406754077540875409754107541175412754137541475415754167541775418754197542075421754227542375424754257542675427754287542975430754317543275433754347543575436754377543875439754407544175442754437544475445754467544775448754497545075451754527545375454754557545675457754587545975460754617546275463754647546575466754677546875469754707547175472754737547475475754767547775478754797548075481754827548375484754857548675487754887548975490754917549275493754947549575496754977549875499755007550175502755037550475505755067550775508755097551075511755127551375514755157551675517755187551975520755217552275523755247552575526755277552875529755307553175532755337553475535755367553775538755397554075541755427554375544755457554675547755487554975550755517555275553755547555575556755577555875559755607556175562755637556475565755667556775568755697557075571755727557375574755757557675577755787557975580755817558275583755847558575586755877558875589755907559175592755937559475595755967559775598755997560075601756027560375604756057560675607756087560975610756117561275613756147561575616756177561875619756207562175622756237562475625756267562775628756297563075631756327563375634756357563675637756387563975640756417564275643756447564575646756477564875649756507565175652756537565475655756567565775658756597566075661756627566375664756657566675667756687566975670756717567275673756747567575676756777567875679756807568175682756837568475685756867568775688756897569075691756927569375694756957569675697756987569975700757017570275703757047570575706757077570875709757107571175712757137571475715757167571775718757197572075721757227572375724757257572675727757287572975730757317573275733757347573575736757377573875739757407574175742757437574475745757467574775748757497575075751757527575375754757557575675757757587575975760757617576275763757647576575766757677576875769757707577175772757737577475775757767577775778757797578075781757827578375784757857578675787757887578975790757917579275793757947579575796757977579875799758007580175802758037580475805758067580775808758097581075811758127581375814758157581675817758187581975820758217582275823758247582575826758277582875829758307583175832758337583475835758367583775838758397584075841758427584375844758457584675847758487584975850758517585275853758547585575856758577585875859758607586175862758637586475865758667586775868758697587075871758727587375874758757587675877758787587975880758817588275883758847588575886758877588875889758907589175892758937589475895758967589775898758997590075901759027590375904759057590675907759087590975910759117591275913759147591575916759177591875919759207592175922759237592475925759267592775928759297593075931759327593375934759357593675937759387593975940759417594275943759447594575946759477594875949759507595175952759537595475955759567595775958759597596075961759627596375964759657596675967759687596975970759717597275973759747597575976759777597875979759807598175982759837598475985759867598775988759897599075991759927599375994759957599675997759987599976000760017600276003760047600576006760077600876009760107601176012760137601476015760167601776018760197602076021760227602376024760257602676027760287602976030760317603276033760347603576036760377603876039760407604176042760437604476045760467604776048760497605076051760527605376054760557605676057760587605976060760617606276063760647606576066760677606876069760707607176072760737607476075760767607776078760797608076081760827608376084760857608676087760887608976090760917609276093760947609576096760977609876099761007610176102761037610476105761067610776108761097611076111761127611376114761157611676117761187611976120761217612276123761247612576126761277612876129761307613176132761337613476135761367613776138761397614076141761427614376144761457614676147761487614976150761517615276153761547615576156761577615876159761607616176162761637616476165761667616776168761697617076171761727617376174761757617676177761787617976180761817618276183761847618576186761877618876189761907619176192761937619476195761967619776198761997620076201762027620376204762057620676207762087620976210762117621276213762147621576216762177621876219762207622176222762237622476225762267622776228762297623076231762327623376234762357623676237762387623976240762417624276243762447624576246762477624876249762507625176252762537625476255762567625776258762597626076261762627626376264762657626676267762687626976270762717627276273762747627576276762777627876279762807628176282762837628476285762867628776288762897629076291762927629376294762957629676297762987629976300763017630276303763047630576306763077630876309763107631176312763137631476315763167631776318763197632076321763227632376324763257632676327763287632976330763317633276333763347633576336763377633876339763407634176342763437634476345763467634776348763497635076351763527635376354763557635676357763587635976360763617636276363763647636576366763677636876369763707637176372763737637476375763767637776378763797638076381763827638376384763857638676387763887638976390763917639276393763947639576396763977639876399764007640176402764037640476405764067640776408764097641076411764127641376414764157641676417764187641976420764217642276423764247642576426764277642876429764307643176432764337643476435764367643776438764397644076441764427644376444764457644676447764487644976450764517645276453764547645576456764577645876459764607646176462764637646476465764667646776468764697647076471764727647376474764757647676477764787647976480764817648276483764847648576486764877648876489764907649176492764937649476495764967649776498764997650076501765027650376504765057650676507765087650976510765117651276513765147651576516765177651876519765207652176522765237652476525765267652776528765297653076531765327653376534765357653676537765387653976540765417654276543765447654576546765477654876549765507655176552765537655476555765567655776558765597656076561765627656376564765657656676567765687656976570765717657276573765747657576576765777657876579765807658176582765837658476585765867658776588765897659076591765927659376594765957659676597765987659976600766017660276603766047660576606766077660876609766107661176612766137661476615766167661776618766197662076621766227662376624766257662676627766287662976630766317663276633766347663576636766377663876639766407664176642766437664476645766467664776648766497665076651766527665376654766557665676657766587665976660766617666276663766647666576666766677666876669766707667176672766737667476675766767667776678766797668076681766827668376684766857668676687766887668976690766917669276693766947669576696766977669876699767007670176702767037670476705767067670776708767097671076711767127671376714767157671676717767187671976720767217672276723767247672576726767277672876729767307673176732767337673476735767367673776738767397674076741767427674376744767457674676747767487674976750767517675276753767547675576756767577675876759767607676176762767637676476765767667676776768767697677076771767727677376774767757677676777767787677976780767817678276783767847678576786767877678876789767907679176792767937679476795767967679776798767997680076801768027680376804768057680676807768087680976810768117681276813768147681576816768177681876819768207682176822768237682476825768267682776828768297683076831768327683376834768357683676837768387683976840768417684276843768447684576846768477684876849768507685176852768537685476855768567685776858768597686076861768627686376864768657686676867768687686976870768717687276873768747687576876768777687876879768807688176882768837688476885768867688776888768897689076891768927689376894768957689676897768987689976900769017690276903769047690576906769077690876909769107691176912769137691476915769167691776918769197692076921769227692376924769257692676927769287692976930769317693276933769347693576936769377693876939769407694176942769437694476945769467694776948769497695076951769527695376954769557695676957769587695976960769617696276963769647696576966769677696876969769707697176972769737697476975769767697776978769797698076981769827698376984769857698676987769887698976990769917699276993769947699576996769977699876999770007700177002770037700477005770067700777008770097701077011770127701377014770157701677017770187701977020770217702277023770247702577026770277702877029770307703177032770337703477035770367703777038770397704077041770427704377044770457704677047770487704977050770517705277053770547705577056770577705877059770607706177062770637706477065770667706777068770697707077071770727707377074770757707677077770787707977080770817708277083770847708577086770877708877089770907709177092770937709477095770967709777098770997710077101771027710377104771057710677107771087710977110771117711277113771147711577116771177711877119771207712177122771237712477125771267712777128771297713077131771327713377134771357713677137771387713977140771417714277143771447714577146771477714877149771507715177152771537715477155771567715777158771597716077161771627716377164771657716677167771687716977170771717717277173771747717577176771777717877179771807718177182771837718477185771867718777188771897719077191771927719377194771957719677197771987719977200772017720277203772047720577206772077720877209772107721177212772137721477215772167721777218772197722077221772227722377224772257722677227772287722977230772317723277233772347723577236772377723877239772407724177242772437724477245772467724777248772497725077251772527725377254772557725677257772587725977260772617726277263772647726577266772677726877269772707727177272772737727477275772767727777278772797728077281772827728377284772857728677287772887728977290772917729277293772947729577296772977729877299773007730177302773037730477305773067730777308773097731077311773127731377314773157731677317773187731977320773217732277323773247732577326773277732877329773307733177332773337733477335773367733777338773397734077341773427734377344773457734677347773487734977350773517735277353773547735577356773577735877359773607736177362773637736477365773667736777368773697737077371773727737377374773757737677377773787737977380773817738277383773847738577386773877738877389773907739177392773937739477395773967739777398773997740077401774027740377404774057740677407774087740977410774117741277413774147741577416774177741877419774207742177422774237742477425774267742777428774297743077431774327743377434774357743677437774387743977440774417744277443774447744577446774477744877449774507745177452774537745477455774567745777458774597746077461774627746377464774657746677467774687746977470774717747277473774747747577476774777747877479774807748177482774837748477485774867748777488774897749077491774927749377494774957749677497774987749977500775017750277503775047750577506775077750877509775107751177512775137751477515775167751777518775197752077521775227752377524775257752677527775287752977530775317753277533775347753577536775377753877539775407754177542775437754477545775467754777548775497755077551775527755377554775557755677557775587755977560775617756277563775647756577566775677756877569775707757177572775737757477575775767757777578775797758077581775827758377584775857758677587775887758977590775917759277593775947759577596775977759877599776007760177602776037760477605776067760777608776097761077611776127761377614776157761677617776187761977620776217762277623776247762577626776277762877629776307763177632776337763477635776367763777638776397764077641776427764377644776457764677647776487764977650776517765277653776547765577656776577765877659776607766177662776637766477665776667766777668776697767077671776727767377674776757767677677776787767977680776817768277683776847768577686776877768877689776907769177692776937769477695776967769777698776997770077701777027770377704777057770677707777087770977710777117771277713777147771577716777177771877719777207772177722777237772477725777267772777728777297773077731777327773377734777357773677737777387773977740777417774277743777447774577746777477774877749777507775177752777537775477755777567775777758777597776077761777627776377764777657776677767777687776977770777717777277773777747777577776777777777877779777807778177782777837778477785777867778777788777897779077791777927779377794777957779677797777987779977800778017780277803778047780577806778077780877809778107781177812778137781477815778167781777818778197782077821778227782377824778257782677827778287782977830778317783277833778347783577836778377783877839778407784177842778437784477845778467784777848778497785077851778527785377854778557785677857778587785977860778617786277863778647786577866778677786877869778707787177872778737787477875778767787777878778797788077881778827788377884778857788677887778887788977890778917789277893778947789577896778977789877899779007790177902779037790477905779067790777908779097791077911779127791377914779157791677917779187791977920779217792277923779247792577926779277792877929779307793177932779337793477935779367793777938779397794077941779427794377944779457794677947779487794977950779517795277953779547795577956779577795877959779607796177962779637796477965779667796777968779697797077971779727797377974779757797677977779787797977980779817798277983779847798577986779877798877989779907799177992779937799477995779967799777998779997800078001780027800378004780057800678007780087800978010780117801278013780147801578016780177801878019780207802178022780237802478025780267802778028780297803078031780327803378034780357803678037780387803978040780417804278043780447804578046780477804878049780507805178052780537805478055780567805778058780597806078061780627806378064780657806678067780687806978070780717807278073780747807578076780777807878079780807808178082780837808478085780867808778088780897809078091780927809378094780957809678097780987809978100781017810278103781047810578106781077810878109781107811178112781137811478115781167811778118781197812078121781227812378124781257812678127781287812978130781317813278133781347813578136781377813878139781407814178142781437814478145781467814778148781497815078151781527815378154781557815678157781587815978160781617816278163781647816578166781677816878169781707817178172781737817478175781767817778178781797818078181781827818378184781857818678187781887818978190781917819278193781947819578196781977819878199782007820178202782037820478205782067820778208782097821078211782127821378214782157821678217782187821978220782217822278223782247822578226782277822878229782307823178232782337823478235782367823778238782397824078241782427824378244782457824678247782487824978250782517825278253782547825578256782577825878259782607826178262782637826478265782667826778268782697827078271782727827378274782757827678277782787827978280782817828278283782847828578286782877828878289782907829178292782937829478295782967829778298782997830078301783027830378304783057830678307783087830978310783117831278313783147831578316783177831878319783207832178322783237832478325783267832778328783297833078331783327833378334783357833678337783387833978340783417834278343783447834578346783477834878349783507835178352783537835478355783567835778358783597836078361783627836378364783657836678367783687836978370783717837278373783747837578376783777837878379783807838178382783837838478385783867838778388783897839078391783927839378394783957839678397783987839978400784017840278403784047840578406784077840878409784107841178412784137841478415784167841778418784197842078421784227842378424784257842678427784287842978430784317843278433784347843578436784377843878439784407844178442784437844478445784467844778448784497845078451784527845378454784557845678457784587845978460784617846278463784647846578466784677846878469784707847178472784737847478475784767847778478784797848078481784827848378484784857848678487784887848978490784917849278493784947849578496784977849878499785007850178502785037850478505785067850778508785097851078511785127851378514785157851678517785187851978520785217852278523785247852578526785277852878529785307853178532785337853478535785367853778538785397854078541785427854378544785457854678547785487854978550785517855278553785547855578556785577855878559785607856178562785637856478565785667856778568785697857078571785727857378574785757857678577785787857978580785817858278583785847858578586785877858878589785907859178592785937859478595785967859778598785997860078601786027860378604786057860678607786087860978610786117861278613786147861578616786177861878619786207862178622786237862478625786267862778628786297863078631786327863378634786357863678637786387863978640786417864278643786447864578646786477864878649786507865178652786537865478655786567865778658786597866078661786627866378664786657866678667786687866978670786717867278673786747867578676786777867878679786807868178682786837868478685786867868778688786897869078691786927869378694786957869678697786987869978700787017870278703787047870578706787077870878709787107871178712787137871478715787167871778718787197872078721787227872378724787257872678727787287872978730787317873278733787347873578736787377873878739787407874178742787437874478745787467874778748787497875078751787527875378754787557875678757787587875978760787617876278763787647876578766787677876878769787707877178772787737877478775787767877778778787797878078781787827878378784787857878678787787887878978790787917879278793787947879578796787977879878799788007880178802788037880478805788067880778808788097881078811788127881378814788157881678817788187881978820788217882278823788247882578826788277882878829788307883178832788337883478835788367883778838788397884078841788427884378844788457884678847788487884978850788517885278853788547885578856788577885878859788607886178862788637886478865788667886778868788697887078871788727887378874788757887678877788787887978880788817888278883788847888578886788877888878889788907889178892788937889478895788967889778898788997890078901789027890378904789057890678907789087890978910789117891278913789147891578916789177891878919789207892178922789237892478925789267892778928789297893078931789327893378934789357893678937789387893978940789417894278943789447894578946789477894878949789507895178952789537895478955789567895778958789597896078961789627896378964789657896678967789687896978970789717897278973789747897578976789777897878979789807898178982789837898478985789867898778988789897899078991789927899378994789957899678997789987899979000790017900279003790047900579006790077900879009790107901179012790137901479015790167901779018790197902079021790227902379024790257902679027790287902979030790317903279033790347903579036790377903879039790407904179042790437904479045790467904779048790497905079051790527905379054790557905679057790587905979060790617906279063790647906579066790677906879069790707907179072790737907479075790767907779078790797908079081790827908379084790857908679087790887908979090790917909279093790947909579096790977909879099791007910179102791037910479105791067910779108791097911079111791127911379114791157911679117791187911979120791217912279123791247912579126791277912879129791307913179132791337913479135791367913779138791397914079141791427914379144791457914679147791487914979150791517915279153791547915579156791577915879159791607916179162791637916479165791667916779168791697917079171791727917379174791757917679177791787917979180791817918279183791847918579186791877918879189791907919179192791937919479195791967919779198791997920079201792027920379204792057920679207792087920979210792117921279213792147921579216792177921879219792207922179222792237922479225792267922779228792297923079231792327923379234792357923679237792387923979240792417924279243792447924579246792477924879249792507925179252792537925479255792567925779258792597926079261792627926379264792657926679267792687926979270792717927279273792747927579276792777927879279792807928179282792837928479285792867928779288792897929079291792927929379294792957929679297792987929979300793017930279303793047930579306793077930879309793107931179312793137931479315793167931779318793197932079321793227932379324793257932679327793287932979330793317933279333793347933579336793377933879339793407934179342793437934479345793467934779348793497935079351793527935379354793557935679357793587935979360793617936279363793647936579366793677936879369793707937179372793737937479375793767937779378793797938079381793827938379384793857938679387793887938979390793917939279393793947939579396793977939879399794007940179402794037940479405794067940779408794097941079411794127941379414794157941679417794187941979420794217942279423794247942579426794277942879429794307943179432794337943479435794367943779438794397944079441794427944379444794457944679447794487944979450794517945279453794547945579456794577945879459794607946179462794637946479465794667946779468794697947079471794727947379474794757947679477794787947979480794817948279483794847948579486794877948879489794907949179492794937949479495794967949779498794997950079501795027950379504795057950679507795087950979510795117951279513795147951579516795177951879519795207952179522795237952479525795267952779528795297953079531795327953379534795357953679537795387953979540795417954279543795447954579546795477954879549795507955179552795537955479555795567955779558795597956079561795627956379564795657956679567795687956979570795717957279573795747957579576795777957879579795807958179582795837958479585795867958779588795897959079591795927959379594795957959679597795987959979600796017960279603796047960579606796077960879609796107961179612796137961479615796167961779618796197962079621796227962379624796257962679627796287962979630796317963279633796347963579636796377963879639796407964179642796437964479645796467964779648796497965079651796527965379654796557965679657796587965979660796617966279663796647966579666796677966879669796707967179672796737967479675796767967779678796797968079681796827968379684796857968679687796887968979690796917969279693796947969579696796977969879699797007970179702797037970479705797067970779708797097971079711797127971379714797157971679717797187971979720797217972279723797247972579726797277972879729797307973179732797337973479735797367973779738797397974079741797427974379744797457974679747797487974979750797517975279753797547975579756797577975879759797607976179762797637976479765797667976779768797697977079771797727977379774797757977679777797787977979780797817978279783797847978579786797877978879789797907979179792797937979479795797967979779798797997980079801798027980379804798057980679807798087980979810798117981279813798147981579816798177981879819798207982179822798237982479825798267982779828798297983079831798327983379834798357983679837798387983979840798417984279843798447984579846798477984879849798507985179852798537985479855798567985779858798597986079861798627986379864798657986679867798687986979870798717987279873798747987579876798777987879879798807988179882798837988479885798867988779888798897989079891798927989379894798957989679897798987989979900799017990279903799047990579906799077990879909799107991179912799137991479915799167991779918799197992079921799227992379924799257992679927799287992979930799317993279933799347993579936799377993879939799407994179942799437994479945799467994779948799497995079951799527995379954799557995679957799587995979960799617996279963799647996579966799677996879969799707997179972799737997479975799767997779978799797998079981799827998379984799857998679987799887998979990799917999279993799947999579996799977999879999800008000180002800038000480005800068000780008800098001080011800128001380014800158001680017800188001980020800218002280023800248002580026800278002880029800308003180032800338003480035800368003780038800398004080041800428004380044800458004680047800488004980050800518005280053800548005580056800578005880059800608006180062800638006480065800668006780068800698007080071800728007380074800758007680077800788007980080800818008280083800848008580086800878008880089800908009180092800938009480095800968009780098800998010080101801028010380104801058010680107801088010980110801118011280113801148011580116801178011880119801208012180122801238012480125801268012780128801298013080131801328013380134801358013680137801388013980140801418014280143801448014580146801478014880149801508015180152801538015480155801568015780158801598016080161801628016380164801658016680167801688016980170801718017280173801748017580176801778017880179801808018180182801838018480185801868018780188801898019080191801928019380194801958019680197801988019980200802018020280203802048020580206802078020880209802108021180212802138021480215802168021780218802198022080221802228022380224802258022680227802288022980230802318023280233802348023580236802378023880239802408024180242802438024480245802468024780248802498025080251802528025380254802558025680257802588025980260802618026280263802648026580266802678026880269802708027180272802738027480275802768027780278802798028080281802828028380284802858028680287802888028980290802918029280293802948029580296802978029880299803008030180302803038030480305803068030780308803098031080311803128031380314803158031680317803188031980320803218032280323803248032580326803278032880329803308033180332803338033480335803368033780338803398034080341803428034380344803458034680347803488034980350803518035280353803548035580356803578035880359803608036180362803638036480365803668036780368803698037080371803728037380374803758037680377803788037980380803818038280383803848038580386803878038880389803908039180392803938039480395803968039780398803998040080401804028040380404804058040680407804088040980410804118041280413804148041580416804178041880419804208042180422804238042480425804268042780428804298043080431804328043380434804358043680437804388043980440804418044280443804448044580446804478044880449804508045180452804538045480455804568045780458804598046080461804628046380464804658046680467804688046980470804718047280473804748047580476804778047880479804808048180482804838048480485804868048780488804898049080491804928049380494804958049680497804988049980500805018050280503805048050580506805078050880509805108051180512805138051480515805168051780518805198052080521805228052380524805258052680527805288052980530805318053280533805348053580536805378053880539805408054180542805438054480545805468054780548805498055080551805528055380554805558055680557805588055980560805618056280563805648056580566805678056880569805708057180572805738057480575805768057780578805798058080581805828058380584805858058680587805888058980590805918059280593805948059580596805978059880599806008060180602806038060480605806068060780608806098061080611806128061380614806158061680617806188061980620806218062280623806248062580626806278062880629806308063180632806338063480635806368063780638806398064080641806428064380644806458064680647806488064980650806518065280653806548065580656806578065880659806608066180662806638066480665806668066780668806698067080671806728067380674806758067680677806788067980680806818068280683806848068580686806878068880689806908069180692806938069480695806968069780698806998070080701807028070380704807058070680707807088070980710807118071280713807148071580716807178071880719807208072180722807238072480725807268072780728807298073080731807328073380734807358073680737807388073980740807418074280743807448074580746807478074880749807508075180752807538075480755807568075780758807598076080761807628076380764807658076680767807688076980770807718077280773807748077580776807778077880779807808078180782807838078480785807868078780788807898079080791807928079380794807958079680797807988079980800808018080280803808048080580806808078080880809808108081180812808138081480815808168081780818808198082080821808228082380824808258082680827808288082980830808318083280833808348083580836808378083880839808408084180842808438084480845808468084780848808498085080851808528085380854808558085680857808588085980860808618086280863808648086580866808678086880869808708087180872808738087480875808768087780878808798088080881808828088380884808858088680887808888088980890808918089280893808948089580896808978089880899809008090180902809038090480905809068090780908809098091080911809128091380914809158091680917809188091980920809218092280923809248092580926809278092880929809308093180932809338093480935809368093780938809398094080941809428094380944809458094680947809488094980950809518095280953809548095580956809578095880959809608096180962809638096480965809668096780968809698097080971809728097380974809758097680977809788097980980809818098280983809848098580986809878098880989809908099180992809938099480995809968099780998809998100081001810028100381004810058100681007810088100981010810118101281013810148101581016810178101881019810208102181022810238102481025810268102781028810298103081031810328103381034810358103681037810388103981040810418104281043810448104581046810478104881049810508105181052810538105481055810568105781058810598106081061810628106381064810658106681067810688106981070810718107281073810748107581076810778107881079810808108181082810838108481085810868108781088810898109081091810928109381094810958109681097810988109981100811018110281103811048110581106811078110881109811108111181112811138111481115811168111781118811198112081121811228112381124811258112681127811288112981130811318113281133811348113581136811378113881139811408114181142811438114481145811468114781148811498115081151811528115381154811558115681157811588115981160811618116281163811648116581166811678116881169811708117181172811738117481175811768117781178811798118081181811828118381184811858118681187811888118981190811918119281193811948119581196811978119881199812008120181202812038120481205812068120781208812098121081211812128121381214812158121681217812188121981220812218122281223812248122581226812278122881229812308123181232812338123481235812368123781238812398124081241812428124381244812458124681247812488124981250812518125281253812548125581256812578125881259812608126181262812638126481265812668126781268812698127081271812728127381274812758127681277812788127981280812818128281283812848128581286812878128881289812908129181292812938129481295812968129781298812998130081301813028130381304813058130681307813088130981310813118131281313813148131581316813178131881319813208132181322813238132481325813268132781328813298133081331813328133381334813358133681337813388133981340813418134281343813448134581346813478134881349813508135181352813538135481355813568135781358813598136081361813628136381364813658136681367813688136981370813718137281373813748137581376813778137881379813808138181382813838138481385813868138781388813898139081391813928139381394813958139681397813988139981400814018140281403814048140581406814078140881409814108141181412814138141481415814168141781418814198142081421814228142381424814258142681427814288142981430814318143281433814348143581436814378143881439814408144181442814438144481445814468144781448814498145081451814528145381454814558145681457814588145981460814618146281463814648146581466814678146881469814708147181472814738147481475814768147781478814798148081481814828148381484814858148681487814888148981490814918149281493814948149581496814978149881499815008150181502815038150481505815068150781508815098151081511815128151381514815158151681517815188151981520815218152281523815248152581526815278152881529815308153181532815338153481535815368153781538815398154081541815428154381544815458154681547815488154981550815518155281553815548155581556815578155881559815608156181562815638156481565815668156781568815698157081571815728157381574815758157681577815788157981580815818158281583815848158581586815878158881589815908159181592815938159481595815968159781598815998160081601816028160381604816058160681607816088160981610816118161281613816148161581616816178161881619816208162181622816238162481625816268162781628816298163081631816328163381634816358163681637816388163981640816418164281643816448164581646816478164881649816508165181652816538165481655816568165781658816598166081661816628166381664816658166681667816688166981670816718167281673816748167581676816778167881679816808168181682816838168481685816868168781688816898169081691816928169381694816958169681697816988169981700817018170281703817048170581706817078170881709817108171181712817138171481715817168171781718817198172081721817228172381724817258172681727817288172981730817318173281733817348173581736817378173881739817408174181742817438174481745817468174781748817498175081751817528175381754817558175681757817588175981760817618176281763817648176581766817678176881769817708177181772817738177481775817768177781778817798178081781817828178381784817858178681787817888178981790817918179281793817948179581796817978179881799818008180181802818038180481805818068180781808818098181081811818128181381814818158181681817818188181981820818218182281823818248182581826818278182881829818308183181832818338183481835818368183781838818398184081841818428184381844818458184681847818488184981850818518185281853818548185581856818578185881859818608186181862818638186481865818668186781868818698187081871818728187381874818758187681877818788187981880818818188281883818848188581886818878188881889818908189181892818938189481895818968189781898818998190081901819028190381904819058190681907819088190981910819118191281913819148191581916819178191881919819208192181922819238192481925819268192781928819298193081931819328193381934819358193681937819388193981940819418194281943819448194581946819478194881949819508195181952819538195481955819568195781958819598196081961819628196381964819658196681967819688196981970819718197281973819748197581976819778197881979819808198181982819838198481985819868198781988819898199081991819928199381994819958199681997819988199982000820018200282003820048200582006820078200882009820108201182012820138201482015820168201782018820198202082021820228202382024820258202682027820288202982030820318203282033820348203582036820378203882039820408204182042820438204482045820468204782048820498205082051820528205382054820558205682057820588205982060820618206282063820648206582066820678206882069820708207182072820738207482075820768207782078820798208082081820828208382084820858208682087820888208982090820918209282093820948209582096820978209882099821008210182102821038210482105821068210782108821098211082111821128211382114821158211682117821188211982120821218212282123821248212582126821278212882129821308213182132821338213482135821368213782138821398214082141821428214382144821458214682147821488214982150821518215282153821548215582156821578215882159821608216182162821638216482165821668216782168821698217082171821728217382174821758217682177821788217982180821818218282183821848218582186821878218882189821908219182192821938219482195821968219782198821998220082201822028220382204822058220682207822088220982210822118221282213822148221582216822178221882219822208222182222822238222482225822268222782228822298223082231822328223382234822358223682237822388223982240822418224282243822448224582246822478224882249822508225182252822538225482255822568225782258822598226082261822628226382264822658226682267822688226982270822718227282273822748227582276822778227882279822808228182282822838228482285822868228782288822898229082291822928229382294822958229682297822988229982300823018230282303823048230582306823078230882309823108231182312823138231482315823168231782318823198232082321823228232382324823258232682327823288232982330823318233282333823348233582336823378233882339823408234182342823438234482345823468234782348823498235082351823528235382354823558235682357823588235982360823618236282363823648236582366823678236882369823708237182372823738237482375823768237782378823798238082381823828238382384823858238682387823888238982390823918239282393823948239582396823978239882399824008240182402824038240482405824068240782408824098241082411824128241382414824158241682417824188241982420824218242282423824248242582426824278242882429824308243182432824338243482435824368243782438824398244082441824428244382444824458244682447824488244982450824518245282453824548245582456824578245882459824608246182462824638246482465824668246782468824698247082471824728247382474824758247682477824788247982480824818248282483824848248582486824878248882489824908249182492824938249482495824968249782498824998250082501825028250382504825058250682507825088250982510825118251282513825148251582516825178251882519825208252182522825238252482525825268252782528825298253082531825328253382534825358253682537825388253982540825418254282543825448254582546825478254882549825508255182552825538255482555825568255782558825598256082561825628256382564825658256682567825688256982570825718257282573825748257582576825778257882579825808258182582825838258482585825868258782588825898259082591825928259382594825958259682597825988259982600826018260282603826048260582606826078260882609826108261182612826138261482615826168261782618826198262082621826228262382624826258262682627826288262982630826318263282633826348263582636826378263882639826408264182642826438264482645826468264782648826498265082651826528265382654826558265682657826588265982660826618266282663826648266582666826678266882669826708267182672826738267482675826768267782678826798268082681826828268382684826858268682687826888268982690826918269282693826948269582696826978269882699827008270182702827038270482705827068270782708827098271082711827128271382714827158271682717827188271982720827218272282723827248272582726827278272882729827308273182732827338273482735827368273782738827398274082741827428274382744827458274682747827488274982750827518275282753827548275582756827578275882759827608276182762827638276482765827668276782768827698277082771827728277382774827758277682777827788277982780827818278282783827848278582786827878278882789827908279182792827938279482795827968279782798827998280082801828028280382804828058280682807828088280982810828118281282813828148281582816828178281882819828208282182822828238282482825828268282782828828298283082831828328283382834828358283682837828388283982840828418284282843828448284582846828478284882849828508285182852828538285482855828568285782858828598286082861828628286382864828658286682867828688286982870828718287282873828748287582876828778287882879828808288182882828838288482885828868288782888828898289082891828928289382894828958289682897828988289982900829018290282903829048290582906829078290882909829108291182912829138291482915829168291782918829198292082921829228292382924829258292682927829288292982930829318293282933829348293582936829378293882939829408294182942829438294482945829468294782948829498295082951829528295382954829558295682957829588295982960829618296282963829648296582966829678296882969829708297182972829738297482975829768297782978829798298082981829828298382984829858298682987829888298982990829918299282993829948299582996829978299882999830008300183002830038300483005830068300783008830098301083011830128301383014830158301683017830188301983020830218302283023830248302583026830278302883029830308303183032830338303483035830368303783038830398304083041830428304383044830458304683047830488304983050830518305283053830548305583056830578305883059830608306183062830638306483065830668306783068830698307083071830728307383074830758307683077830788307983080830818308283083830848308583086830878308883089830908309183092830938309483095830968309783098830998310083101831028310383104831058310683107831088310983110831118311283113831148311583116831178311883119831208312183122831238312483125831268312783128831298313083131831328313383134831358313683137831388313983140831418314283143831448314583146831478314883149831508315183152831538315483155831568315783158831598316083161831628316383164831658316683167831688316983170831718317283173831748317583176831778317883179831808318183182831838318483185831868318783188831898319083191831928319383194831958319683197831988319983200832018320283203832048320583206832078320883209832108321183212832138321483215832168321783218832198322083221832228322383224832258322683227832288322983230832318323283233832348323583236832378323883239832408324183242832438324483245832468324783248832498325083251832528325383254832558325683257832588325983260832618326283263832648326583266832678326883269832708327183272832738327483275832768327783278832798328083281832828328383284832858328683287832888328983290832918329283293832948329583296832978329883299833008330183302833038330483305833068330783308833098331083311833128331383314833158331683317833188331983320833218332283323833248332583326833278332883329833308333183332833338333483335833368333783338833398334083341833428334383344833458334683347833488334983350833518335283353833548335583356833578335883359833608336183362833638336483365833668336783368833698337083371833728337383374833758337683377833788337983380833818338283383833848338583386833878338883389833908339183392833938339483395833968339783398833998340083401834028340383404834058340683407834088340983410834118341283413834148341583416834178341883419834208342183422834238342483425834268342783428834298343083431834328343383434834358343683437834388343983440834418344283443834448344583446834478344883449834508345183452834538345483455834568345783458834598346083461834628346383464834658346683467834688346983470834718347283473834748347583476834778347883479834808348183482834838348483485834868348783488834898349083491834928349383494834958349683497834988349983500835018350283503835048350583506835078350883509835108351183512835138351483515835168351783518835198352083521835228352383524835258352683527835288352983530835318353283533835348353583536835378353883539835408354183542835438354483545835468354783548835498355083551835528355383554835558355683557835588355983560835618356283563835648356583566835678356883569835708357183572835738357483575835768357783578835798358083581835828358383584835858358683587835888358983590835918359283593835948359583596835978359883599836008360183602836038360483605836068360783608836098361083611836128361383614836158361683617836188361983620836218362283623836248362583626836278362883629836308363183632836338363483635836368363783638836398364083641836428364383644836458364683647836488364983650836518365283653836548365583656836578365883659836608366183662836638366483665836668366783668836698367083671836728367383674836758367683677836788367983680836818368283683836848368583686836878368883689836908369183692836938369483695836968369783698836998370083701837028370383704837058370683707837088370983710837118371283713837148371583716837178371883719837208372183722837238372483725837268372783728837298373083731837328373383734837358373683737837388373983740837418374283743837448374583746837478374883749837508375183752837538375483755837568375783758837598376083761837628376383764837658376683767837688376983770837718377283773837748377583776837778377883779837808378183782837838378483785837868378783788837898379083791837928379383794837958379683797837988379983800838018380283803838048380583806838078380883809838108381183812838138381483815838168381783818838198382083821838228382383824838258382683827838288382983830838318383283833838348383583836838378383883839838408384183842838438384483845838468384783848838498385083851838528385383854838558385683857838588385983860838618386283863838648386583866838678386883869838708387183872838738387483875838768387783878838798388083881838828388383884838858388683887838888388983890838918389283893838948389583896838978389883899839008390183902839038390483905839068390783908839098391083911839128391383914839158391683917839188391983920839218392283923839248392583926839278392883929839308393183932839338393483935839368393783938839398394083941839428394383944839458394683947839488394983950839518395283953839548395583956839578395883959839608396183962839638396483965839668396783968839698397083971839728397383974839758397683977839788397983980839818398283983839848398583986839878398883989839908399183992839938399483995839968399783998839998400084001840028400384004840058400684007840088400984010840118401284013840148401584016840178401884019840208402184022840238402484025840268402784028840298403084031840328403384034840358403684037840388403984040840418404284043840448404584046840478404884049840508405184052840538405484055840568405784058840598406084061840628406384064840658406684067840688406984070840718407284073840748407584076840778407884079840808408184082840838408484085840868408784088840898409084091840928409384094840958409684097840988409984100841018410284103841048410584106841078410884109841108411184112841138411484115841168411784118841198412084121841228412384124841258412684127841288412984130841318413284133841348413584136841378413884139841408414184142841438414484145841468414784148841498415084151841528415384154841558415684157841588415984160841618416284163841648416584166841678416884169841708417184172841738417484175841768417784178841798418084181841828418384184841858418684187841888418984190841918419284193841948419584196841978419884199842008420184202842038420484205842068420784208842098421084211842128421384214842158421684217842188421984220842218422284223842248422584226842278422884229842308423184232842338423484235842368423784238842398424084241842428424384244842458424684247842488424984250842518425284253842548425584256842578425884259842608426184262842638426484265842668426784268842698427084271842728427384274842758427684277842788427984280842818428284283842848428584286842878428884289842908429184292842938429484295842968429784298842998430084301843028430384304843058430684307843088430984310843118431284313843148431584316843178431884319843208432184322843238432484325843268432784328843298433084331843328433384334843358433684337843388433984340843418434284343843448434584346843478434884349843508435184352843538435484355843568435784358843598436084361843628436384364843658436684367843688436984370843718437284373843748437584376843778437884379843808438184382843838438484385843868438784388843898439084391843928439384394843958439684397843988439984400844018440284403844048440584406844078440884409844108441184412844138441484415844168441784418844198442084421844228442384424844258442684427844288442984430844318443284433844348443584436844378443884439844408444184442844438444484445844468444784448844498445084451844528445384454844558445684457844588445984460844618446284463844648446584466844678446884469844708447184472844738447484475844768447784478844798448084481844828448384484844858448684487844888448984490844918449284493844948449584496844978449884499845008450184502845038450484505845068450784508845098451084511845128451384514845158451684517845188451984520845218452284523845248452584526845278452884529845308453184532845338453484535845368453784538845398454084541845428454384544845458454684547845488454984550845518455284553845548455584556845578455884559845608456184562845638456484565845668456784568845698457084571845728457384574845758457684577845788457984580845818458284583845848458584586845878458884589845908459184592845938459484595845968459784598845998460084601846028460384604846058460684607846088460984610846118461284613846148461584616846178461884619846208462184622846238462484625846268462784628846298463084631846328463384634846358463684637846388463984640846418464284643846448464584646846478464884649846508465184652846538465484655846568465784658846598466084661846628466384664846658466684667846688466984670846718467284673846748467584676846778467884679846808468184682846838468484685846868468784688846898469084691846928469384694846958469684697846988469984700847018470284703847048470584706847078470884709847108471184712847138471484715847168471784718847198472084721847228472384724847258472684727847288472984730847318473284733847348473584736847378473884739847408474184742847438474484745847468474784748847498475084751847528475384754847558475684757847588475984760847618476284763847648476584766847678476884769847708477184772847738477484775847768477784778847798478084781847828478384784847858478684787847888478984790847918479284793847948479584796847978479884799848008480184802848038480484805848068480784808848098481084811848128481384814848158481684817848188481984820848218482284823848248482584826848278482884829848308483184832848338483484835848368483784838848398484084841848428484384844848458484684847848488484984850848518485284853848548485584856848578485884859848608486184862848638486484865848668486784868848698487084871848728487384874848758487684877848788487984880848818488284883848848488584886848878488884889848908489184892848938489484895848968489784898848998490084901849028490384904849058490684907849088490984910849118491284913849148491584916849178491884919849208492184922849238492484925849268492784928849298493084931849328493384934849358493684937849388493984940849418494284943849448494584946849478494884949849508495184952849538495484955849568495784958849598496084961849628496384964849658496684967849688496984970849718497284973849748497584976849778497884979849808498184982849838498484985849868498784988849898499084991849928499384994849958499684997849988499985000850018500285003850048500585006850078500885009850108501185012850138501485015850168501785018850198502085021850228502385024850258502685027850288502985030850318503285033850348503585036850378503885039850408504185042850438504485045850468504785048850498505085051850528505385054850558505685057850588505985060850618506285063850648506585066850678506885069850708507185072850738507485075850768507785078850798508085081850828508385084850858508685087850888508985090850918509285093850948509585096850978509885099851008510185102851038510485105851068510785108851098511085111851128511385114851158511685117851188511985120851218512285123851248512585126851278512885129851308513185132851338513485135851368513785138851398514085141851428514385144851458514685147851488514985150851518515285153851548515585156851578515885159851608516185162851638516485165851668516785168851698517085171851728517385174851758517685177851788517985180851818518285183851848518585186851878518885189851908519185192851938519485195851968519785198851998520085201852028520385204852058520685207852088520985210852118521285213852148521585216852178521885219852208522185222852238522485225852268522785228852298523085231852328523385234852358523685237852388523985240852418524285243852448524585246852478524885249852508525185252852538525485255852568525785258852598526085261852628526385264852658526685267852688526985270852718527285273852748527585276852778527885279852808528185282852838528485285852868528785288852898529085291852928529385294852958529685297852988529985300853018530285303853048530585306853078530885309853108531185312853138531485315853168531785318853198532085321853228532385324853258532685327853288532985330853318533285333853348533585336853378533885339853408534185342853438534485345853468534785348853498535085351853528535385354853558535685357853588535985360853618536285363853648536585366853678536885369853708537185372853738537485375853768537785378853798538085381853828538385384853858538685387853888538985390853918539285393853948539585396853978539885399854008540185402854038540485405854068540785408854098541085411854128541385414854158541685417854188541985420854218542285423854248542585426854278542885429854308543185432854338543485435854368543785438854398544085441854428544385444854458544685447854488544985450854518545285453854548545585456854578545885459854608546185462854638546485465854668546785468854698547085471854728547385474854758547685477854788547985480854818548285483854848548585486854878548885489854908549185492854938549485495854968549785498854998550085501855028550385504855058550685507855088550985510855118551285513855148551585516855178551885519855208552185522855238552485525855268552785528855298553085531855328553385534855358553685537855388553985540855418554285543855448554585546855478554885549855508555185552855538555485555855568555785558855598556085561855628556385564855658556685567855688556985570855718557285573855748557585576855778557885579855808558185582855838558485585855868558785588855898559085591855928559385594855958559685597855988559985600856018560285603856048560585606856078560885609856108561185612856138561485615856168561785618856198562085621856228562385624856258562685627856288562985630856318563285633856348563585636856378563885639856408564185642856438564485645856468564785648856498565085651856528565385654856558565685657856588565985660856618566285663856648566585666856678566885669856708567185672856738567485675856768567785678856798568085681856828568385684856858568685687856888568985690856918569285693856948569585696856978569885699857008570185702857038570485705857068570785708857098571085711857128571385714857158571685717857188571985720857218572285723857248572585726857278572885729857308573185732857338573485735857368573785738857398574085741857428574385744857458574685747857488574985750857518575285753857548575585756857578575885759857608576185762857638576485765857668576785768857698577085771857728577385774857758577685777857788577985780857818578285783857848578585786857878578885789857908579185792857938579485795857968579785798857998580085801858028580385804858058580685807858088580985810858118581285813858148581585816858178581885819858208582185822858238582485825858268582785828858298583085831858328583385834858358583685837858388583985840858418584285843858448584585846858478584885849858508585185852858538585485855858568585785858858598586085861858628586385864858658586685867858688586985870858718587285873858748587585876858778587885879858808588185882858838588485885858868588785888858898589085891858928589385894858958589685897858988589985900859018590285903859048590585906859078590885909859108591185912859138591485915859168591785918859198592085921859228592385924859258592685927859288592985930859318593285933859348593585936859378593885939859408594185942859438594485945859468594785948859498595085951859528595385954859558595685957859588595985960859618596285963859648596585966859678596885969859708597185972859738597485975859768597785978859798598085981859828598385984859858598685987859888598985990859918599285993859948599585996859978599885999860008600186002860038600486005860068600786008860098601086011860128601386014860158601686017860188601986020860218602286023860248602586026860278602886029860308603186032860338603486035860368603786038860398604086041860428604386044860458604686047860488604986050860518605286053860548605586056860578605886059860608606186062860638606486065860668606786068860698607086071860728607386074860758607686077860788607986080860818608286083860848608586086860878608886089860908609186092860938609486095860968609786098860998610086101861028610386104861058610686107861088610986110861118611286113861148611586116861178611886119861208612186122861238612486125861268612786128861298613086131861328613386134861358613686137861388613986140861418614286143861448614586146861478614886149861508615186152861538615486155861568615786158861598616086161861628616386164861658616686167861688616986170861718617286173861748617586176861778617886179861808618186182861838618486185861868618786188861898619086191861928619386194861958619686197861988619986200862018620286203862048620586206862078620886209862108621186212862138621486215862168621786218862198622086221862228622386224862258622686227862288622986230862318623286233862348623586236862378623886239862408624186242862438624486245862468624786248862498625086251862528625386254862558625686257862588625986260862618626286263862648626586266862678626886269862708627186272862738627486275862768627786278862798628086281862828628386284862858628686287862888628986290862918629286293862948629586296862978629886299863008630186302863038630486305863068630786308863098631086311863128631386314863158631686317863188631986320863218632286323863248632586326863278632886329863308633186332863338633486335863368633786338863398634086341863428634386344863458634686347863488634986350863518635286353863548635586356863578635886359863608636186362863638636486365863668636786368863698637086371863728637386374863758637686377863788637986380863818638286383863848638586386863878638886389863908639186392863938639486395863968639786398863998640086401864028640386404864058640686407864088640986410864118641286413864148641586416864178641886419864208642186422864238642486425864268642786428864298643086431864328643386434864358643686437864388643986440864418644286443864448644586446864478644886449864508645186452864538645486455864568645786458864598646086461864628646386464864658646686467864688646986470864718647286473864748647586476864778647886479864808648186482864838648486485864868648786488864898649086491864928649386494864958649686497864988649986500865018650286503865048650586506865078650886509865108651186512865138651486515865168651786518865198652086521865228652386524865258652686527865288652986530865318653286533865348653586536865378653886539865408654186542865438654486545865468654786548865498655086551865528655386554865558655686557865588655986560865618656286563865648656586566865678656886569865708657186572865738657486575865768657786578865798658086581865828658386584865858658686587865888658986590865918659286593865948659586596865978659886599866008660186602866038660486605866068660786608866098661086611866128661386614866158661686617866188661986620866218662286623866248662586626866278662886629866308663186632866338663486635866368663786638866398664086641866428664386644866458664686647866488664986650866518665286653866548665586656866578665886659866608666186662866638666486665866668666786668866698667086671866728667386674866758667686677866788667986680866818668286683866848668586686866878668886689866908669186692866938669486695866968669786698866998670086701867028670386704867058670686707867088670986710867118671286713867148671586716867178671886719867208672186722867238672486725867268672786728867298673086731867328673386734867358673686737867388673986740867418674286743867448674586746867478674886749867508675186752867538675486755867568675786758867598676086761867628676386764867658676686767867688676986770867718677286773867748677586776867778677886779867808678186782867838678486785867868678786788867898679086791867928679386794867958679686797867988679986800868018680286803868048680586806868078680886809868108681186812868138681486815868168681786818868198682086821868228682386824868258682686827868288682986830868318683286833868348683586836868378683886839868408684186842868438684486845868468684786848868498685086851868528685386854868558685686857868588685986860868618686286863868648686586866868678686886869868708687186872868738687486875868768687786878868798688086881868828688386884868858688686887868888688986890868918689286893868948689586896868978689886899869008690186902869038690486905869068690786908869098691086911869128691386914869158691686917869188691986920869218692286923869248692586926869278692886929869308693186932869338693486935869368693786938869398694086941869428694386944869458694686947869488694986950869518695286953869548695586956869578695886959869608696186962869638696486965869668696786968869698697086971869728697386974869758697686977869788697986980869818698286983869848698586986869878698886989869908699186992869938699486995869968699786998869998700087001870028700387004870058700687007870088700987010870118701287013870148701587016870178701887019870208702187022870238702487025870268702787028870298703087031870328703387034870358703687037870388703987040870418704287043870448704587046870478704887049870508705187052870538705487055870568705787058870598706087061870628706387064870658706687067870688706987070870718707287073870748707587076870778707887079870808708187082870838708487085870868708787088870898709087091870928709387094870958709687097870988709987100871018710287103871048710587106871078710887109871108711187112871138711487115871168711787118871198712087121871228712387124871258712687127871288712987130871318713287133871348713587136871378713887139871408714187142871438714487145871468714787148871498715087151871528715387154871558715687157871588715987160871618716287163871648716587166871678716887169871708717187172871738717487175871768717787178871798718087181871828718387184871858718687187871888718987190871918719287193871948719587196871978719887199872008720187202872038720487205872068720787208872098721087211872128721387214872158721687217872188721987220872218722287223872248722587226872278722887229872308723187232872338723487235872368723787238872398724087241872428724387244872458724687247872488724987250872518725287253872548725587256872578725887259872608726187262872638726487265872668726787268872698727087271872728727387274872758727687277872788727987280872818728287283872848728587286872878728887289872908729187292872938729487295872968729787298872998730087301873028730387304873058730687307873088730987310873118731287313873148731587316873178731887319873208732187322873238732487325873268732787328873298733087331873328733387334873358733687337873388733987340873418734287343873448734587346873478734887349873508735187352873538735487355873568735787358873598736087361873628736387364873658736687367873688736987370873718737287373873748737587376873778737887379873808738187382873838738487385873868738787388873898739087391873928739387394873958739687397873988739987400874018740287403874048740587406874078740887409874108741187412874138741487415874168741787418874198742087421874228742387424874258742687427874288742987430874318743287433874348743587436874378743887439874408744187442874438744487445874468744787448874498745087451874528745387454874558745687457874588745987460874618746287463874648746587466874678746887469874708747187472874738747487475874768747787478874798748087481874828748387484874858748687487874888748987490874918749287493874948749587496874978749887499875008750187502875038750487505875068750787508875098751087511875128751387514875158751687517875188751987520875218752287523875248752587526875278752887529875308753187532875338753487535875368753787538875398754087541875428754387544875458754687547875488754987550875518755287553875548755587556875578755887559875608756187562875638756487565875668756787568875698757087571875728757387574875758757687577875788757987580875818758287583875848758587586875878758887589875908759187592875938759487595875968759787598875998760087601876028760387604876058760687607876088760987610876118761287613876148761587616876178761887619876208762187622876238762487625876268762787628876298763087631876328763387634876358763687637876388763987640876418764287643876448764587646876478764887649876508765187652876538765487655876568765787658876598766087661876628766387664876658766687667876688766987670876718767287673876748767587676876778767887679876808768187682876838768487685876868768787688876898769087691876928769387694876958769687697876988769987700877018770287703877048770587706877078770887709877108771187712877138771487715877168771787718877198772087721877228772387724877258772687727877288772987730877318773287733877348773587736877378773887739877408774187742877438774487745877468774787748877498775087751877528775387754877558775687757877588775987760877618776287763877648776587766877678776887769877708777187772877738777487775877768777787778877798778087781877828778387784877858778687787877888778987790877918779287793877948779587796877978779887799878008780187802878038780487805878068780787808878098781087811878128781387814878158781687817878188781987820878218782287823878248782587826878278782887829878308783187832878338783487835878368783787838878398784087841878428784387844878458784687847878488784987850878518785287853878548785587856878578785887859878608786187862878638786487865878668786787868878698787087871878728787387874878758787687877878788787987880878818788287883878848788587886878878788887889878908789187892878938789487895878968789787898878998790087901879028790387904879058790687907879088790987910879118791287913879148791587916879178791887919879208792187922879238792487925879268792787928879298793087931879328793387934879358793687937879388793987940879418794287943879448794587946879478794887949879508795187952879538795487955879568795787958879598796087961879628796387964879658796687967879688796987970879718797287973879748797587976879778797887979879808798187982879838798487985879868798787988879898799087991879928799387994879958799687997879988799988000880018800288003880048800588006880078800888009880108801188012880138801488015880168801788018880198802088021880228802388024880258802688027880288802988030880318803288033880348803588036880378803888039880408804188042880438804488045880468804788048880498805088051880528805388054880558805688057880588805988060880618806288063880648806588066880678806888069880708807188072880738807488075880768807788078880798808088081880828808388084880858808688087880888808988090880918809288093880948809588096880978809888099881008810188102881038810488105881068810788108881098811088111881128811388114881158811688117881188811988120881218812288123881248812588126881278812888129881308813188132881338813488135881368813788138881398814088141881428814388144881458814688147881488814988150881518815288153881548815588156881578815888159881608816188162881638816488165881668816788168881698817088171881728817388174881758817688177881788817988180881818818288183881848818588186881878818888189881908819188192881938819488195881968819788198881998820088201882028820388204882058820688207882088820988210882118821288213882148821588216882178821888219882208822188222882238822488225882268822788228882298823088231882328823388234882358823688237882388823988240882418824288243882448824588246882478824888249882508825188252882538825488255882568825788258882598826088261882628826388264882658826688267882688826988270882718827288273882748827588276882778827888279882808828188282882838828488285882868828788288882898829088291882928829388294882958829688297882988829988300883018830288303883048830588306883078830888309883108831188312883138831488315883168831788318883198832088321883228832388324883258832688327883288832988330883318833288333883348833588336883378833888339883408834188342883438834488345883468834788348883498835088351883528835388354883558835688357883588835988360883618836288363883648836588366883678836888369883708837188372883738837488375883768837788378883798838088381883828838388384883858838688387883888838988390883918839288393883948839588396883978839888399884008840188402884038840488405884068840788408884098841088411884128841388414884158841688417884188841988420884218842288423884248842588426884278842888429884308843188432884338843488435884368843788438884398844088441884428844388444884458844688447884488844988450884518845288453884548845588456884578845888459884608846188462884638846488465884668846788468884698847088471884728847388474884758847688477884788847988480884818848288483884848848588486884878848888489884908849188492884938849488495884968849788498884998850088501885028850388504885058850688507885088850988510885118851288513885148851588516885178851888519885208852188522885238852488525885268852788528885298853088531885328853388534885358853688537885388853988540885418854288543885448854588546885478854888549885508855188552885538855488555885568855788558885598856088561885628856388564885658856688567885688856988570885718857288573885748857588576885778857888579885808858188582885838858488585885868858788588885898859088591885928859388594885958859688597885988859988600886018860288603886048860588606886078860888609886108861188612886138861488615886168861788618886198862088621886228862388624886258862688627886288862988630886318863288633886348863588636886378863888639886408864188642886438864488645886468864788648886498865088651886528865388654886558865688657886588865988660886618866288663886648866588666886678866888669886708867188672886738867488675886768867788678886798868088681886828868388684886858868688687886888868988690886918869288693886948869588696886978869888699887008870188702887038870488705887068870788708887098871088711887128871388714887158871688717887188871988720887218872288723887248872588726887278872888729887308873188732887338873488735887368873788738887398874088741887428874388744887458874688747887488874988750887518875288753887548875588756887578875888759887608876188762887638876488765887668876788768887698877088771887728877388774887758877688777887788877988780887818878288783887848878588786887878878888789887908879188792887938879488795887968879788798887998880088801888028880388804888058880688807888088880988810888118881288813888148881588816888178881888819888208882188822888238882488825888268882788828888298883088831888328883388834888358883688837888388883988840888418884288843888448884588846888478884888849888508885188852888538885488855888568885788858888598886088861888628886388864888658886688867888688886988870888718887288873888748887588876888778887888879888808888188882888838888488885888868888788888888898889088891888928889388894888958889688897888988889988900889018890288903889048890588906889078890888909889108891188912889138891488915889168891788918889198892088921889228892388924889258892688927889288892988930889318893288933889348893588936889378893888939889408894188942889438894488945889468894788948889498895088951889528895388954889558895688957889588895988960889618896288963889648896588966889678896888969889708897188972889738897488975889768897788978889798898088981889828898388984889858898688987889888898988990889918899288993889948899588996889978899888999890008900189002890038900489005890068900789008890098901089011890128901389014890158901689017890188901989020890218902289023890248902589026890278902889029890308903189032890338903489035890368903789038890398904089041890428904389044890458904689047890488904989050890518905289053890548905589056890578905889059890608906189062890638906489065890668906789068890698907089071890728907389074890758907689077890788907989080890818908289083890848908589086890878908889089890908909189092890938909489095890968909789098890998910089101891028910389104891058910689107891088910989110891118911289113891148911589116891178911889119891208912189122891238912489125891268912789128891298913089131891328913389134891358913689137891388913989140891418914289143891448914589146891478914889149891508915189152891538915489155891568915789158891598916089161891628916389164891658916689167891688916989170891718917289173891748917589176891778917889179891808918189182891838918489185891868918789188891898919089191891928919389194891958919689197891988919989200892018920289203892048920589206892078920889209892108921189212892138921489215892168921789218892198922089221892228922389224892258922689227892288922989230892318923289233892348923589236892378923889239892408924189242892438924489245892468924789248892498925089251892528925389254892558925689257892588925989260892618926289263892648926589266892678926889269892708927189272892738927489275892768927789278892798928089281892828928389284892858928689287892888928989290892918929289293892948929589296892978929889299893008930189302893038930489305893068930789308893098931089311893128931389314893158931689317893188931989320893218932289323893248932589326893278932889329893308933189332893338933489335893368933789338893398934089341893428934389344893458934689347893488934989350893518935289353893548935589356893578935889359893608936189362893638936489365893668936789368893698937089371893728937389374893758937689377893788937989380893818938289383893848938589386893878938889389893908939189392893938939489395893968939789398893998940089401894028940389404894058940689407894088940989410894118941289413894148941589416894178941889419894208942189422894238942489425894268942789428894298943089431894328943389434894358943689437894388943989440894418944289443894448944589446894478944889449894508945189452894538945489455894568945789458894598946089461894628946389464894658946689467894688946989470894718947289473894748947589476894778947889479894808948189482894838948489485894868948789488894898949089491894928949389494894958949689497894988949989500895018950289503895048950589506895078950889509895108951189512895138951489515895168951789518895198952089521895228952389524895258952689527895288952989530895318953289533895348953589536895378953889539895408954189542895438954489545895468954789548895498955089551895528955389554895558955689557895588955989560895618956289563895648956589566895678956889569895708957189572895738957489575895768957789578895798958089581895828958389584895858958689587895888958989590895918959289593895948959589596895978959889599896008960189602896038960489605896068960789608896098961089611896128961389614896158961689617896188961989620896218962289623896248962589626896278962889629896308963189632896338963489635896368963789638896398964089641896428964389644896458964689647896488964989650896518965289653896548965589656896578965889659896608966189662896638966489665896668966789668896698967089671896728967389674896758967689677896788967989680896818968289683896848968589686896878968889689896908969189692896938969489695896968969789698896998970089701897028970389704897058970689707897088970989710897118971289713897148971589716897178971889719897208972189722897238972489725897268972789728897298973089731897328973389734897358973689737897388973989740897418974289743897448974589746897478974889749897508975189752897538975489755897568975789758897598976089761897628976389764897658976689767897688976989770897718977289773897748977589776897778977889779897808978189782897838978489785897868978789788897898979089791897928979389794897958979689797897988979989800898018980289803898048980589806898078980889809898108981189812898138981489815898168981789818898198982089821898228982389824898258982689827898288982989830898318983289833898348983589836898378983889839898408984189842898438984489845898468984789848898498985089851898528985389854898558985689857898588985989860898618986289863898648986589866898678986889869898708987189872898738987489875898768987789878898798988089881898828988389884898858988689887898888988989890898918989289893898948989589896898978989889899899008990189902899038990489905899068990789908899098991089911899128991389914899158991689917899188991989920899218992289923899248992589926899278992889929899308993189932899338993489935899368993789938899398994089941899428994389944899458994689947899488994989950899518995289953899548995589956899578995889959899608996189962899638996489965899668996789968899698997089971899728997389974899758997689977899788997989980899818998289983899848998589986899878998889989899908999189992899938999489995899968999789998899999000090001900029000390004900059000690007900089000990010900119001290013900149001590016900179001890019900209002190022900239002490025900269002790028900299003090031900329003390034900359003690037900389003990040900419004290043900449004590046900479004890049900509005190052900539005490055900569005790058900599006090061900629006390064900659006690067900689006990070900719007290073900749007590076900779007890079900809008190082900839008490085900869008790088900899009090091900929009390094900959009690097900989009990100901019010290103901049010590106901079010890109901109011190112901139011490115901169011790118901199012090121901229012390124901259012690127901289012990130901319013290133901349013590136901379013890139901409014190142901439014490145901469014790148901499015090151901529015390154901559015690157901589015990160901619016290163901649016590166901679016890169901709017190172901739017490175901769017790178901799018090181901829018390184901859018690187901889018990190901919019290193901949019590196901979019890199902009020190202902039020490205902069020790208902099021090211902129021390214902159021690217902189021990220902219022290223902249022590226902279022890229902309023190232902339023490235902369023790238902399024090241902429024390244902459024690247902489024990250902519025290253902549025590256902579025890259902609026190262902639026490265902669026790268902699027090271902729027390274902759027690277902789027990280902819028290283902849028590286902879028890289902909029190292902939029490295902969029790298902999030090301903029030390304903059030690307903089030990310903119031290313903149031590316903179031890319903209032190322903239032490325903269032790328903299033090331903329033390334903359033690337903389033990340903419034290343903449034590346903479034890349903509035190352903539035490355903569035790358903599036090361903629036390364903659036690367903689036990370903719037290373903749037590376903779037890379903809038190382903839038490385903869038790388903899039090391903929039390394903959039690397903989039990400904019040290403904049040590406904079040890409904109041190412904139041490415904169041790418904199042090421904229042390424904259042690427904289042990430904319043290433904349043590436904379043890439904409044190442904439044490445904469044790448904499045090451904529045390454904559045690457904589045990460904619046290463904649046590466904679046890469904709047190472904739047490475904769047790478904799048090481904829048390484904859048690487904889048990490904919049290493904949049590496904979049890499905009050190502905039050490505905069050790508905099051090511905129051390514905159051690517905189051990520905219052290523905249052590526905279052890529905309053190532905339053490535905369053790538905399054090541905429054390544905459054690547905489054990550905519055290553905549055590556905579055890559905609056190562905639056490565905669056790568905699057090571905729057390574905759057690577905789057990580905819058290583905849058590586905879058890589905909059190592905939059490595905969059790598905999060090601906029060390604906059060690607906089060990610906119061290613906149061590616906179061890619906209062190622906239062490625906269062790628906299063090631906329063390634906359063690637906389063990640906419064290643906449064590646906479064890649906509065190652906539065490655906569065790658906599066090661906629066390664906659066690667906689066990670906719067290673906749067590676906779067890679906809068190682906839068490685906869068790688906899069090691906929069390694906959069690697906989069990700907019070290703907049070590706907079070890709907109071190712907139071490715907169071790718907199072090721907229072390724907259072690727907289072990730907319073290733907349073590736907379073890739907409074190742907439074490745907469074790748907499075090751907529075390754907559075690757907589075990760907619076290763907649076590766907679076890769907709077190772907739077490775907769077790778907799078090781907829078390784907859078690787907889078990790907919079290793907949079590796907979079890799908009080190802908039080490805908069080790808908099081090811908129081390814908159081690817908189081990820908219082290823908249082590826908279082890829908309083190832908339083490835908369083790838908399084090841908429084390844908459084690847908489084990850908519085290853908549085590856908579085890859908609086190862908639086490865908669086790868908699087090871908729087390874908759087690877908789087990880908819088290883908849088590886908879088890889908909089190892908939089490895908969089790898908999090090901909029090390904909059090690907909089090990910909119091290913909149091590916909179091890919909209092190922909239092490925909269092790928909299093090931909329093390934909359093690937909389093990940909419094290943909449094590946909479094890949909509095190952909539095490955909569095790958909599096090961909629096390964909659096690967909689096990970909719097290973909749097590976909779097890979909809098190982909839098490985909869098790988909899099090991909929099390994909959099690997909989099991000910019100291003910049100591006910079100891009910109101191012910139101491015910169101791018910199102091021910229102391024910259102691027910289102991030910319103291033910349103591036910379103891039910409104191042910439104491045910469104791048910499105091051910529105391054910559105691057910589105991060910619106291063910649106591066910679106891069910709107191072910739107491075910769107791078910799108091081910829108391084910859108691087910889108991090910919109291093910949109591096910979109891099911009110191102911039110491105911069110791108911099111091111911129111391114911159111691117911189111991120911219112291123911249112591126911279112891129911309113191132911339113491135911369113791138911399114091141911429114391144911459114691147911489114991150911519115291153911549115591156911579115891159911609116191162911639116491165911669116791168911699117091171911729117391174911759117691177911789117991180911819118291183911849118591186911879118891189911909119191192911939119491195911969119791198911999120091201912029120391204912059120691207912089120991210912119121291213912149121591216912179121891219912209122191222912239122491225912269122791228912299123091231912329123391234912359123691237912389123991240912419124291243912449124591246912479124891249912509125191252912539125491255912569125791258912599126091261912629126391264912659126691267912689126991270912719127291273912749127591276912779127891279912809128191282912839128491285912869128791288912899129091291912929129391294912959129691297912989129991300913019130291303913049130591306913079130891309913109131191312913139131491315913169131791318913199132091321913229132391324913259132691327913289132991330913319133291333913349133591336913379133891339913409134191342913439134491345913469134791348913499135091351913529135391354913559135691357913589135991360913619136291363913649136591366913679136891369913709137191372913739137491375913769137791378913799138091381913829138391384913859138691387913889138991390913919139291393913949139591396913979139891399914009140191402914039140491405914069140791408914099141091411914129141391414914159141691417914189141991420914219142291423914249142591426914279142891429914309143191432914339143491435914369143791438914399144091441914429144391444914459144691447914489144991450914519145291453914549145591456914579145891459914609146191462914639146491465914669146791468914699147091471914729147391474914759147691477914789147991480914819148291483914849148591486914879148891489914909149191492914939149491495914969149791498914999150091501915029150391504915059150691507915089150991510915119151291513915149151591516915179151891519915209152191522915239152491525915269152791528915299153091531915329153391534915359153691537915389153991540915419154291543915449154591546915479154891549915509155191552915539155491555915569155791558915599156091561915629156391564915659156691567915689156991570915719157291573915749157591576915779157891579915809158191582915839158491585915869158791588915899159091591915929159391594915959159691597915989159991600916019160291603916049160591606916079160891609916109161191612916139161491615916169161791618916199162091621916229162391624916259162691627916289162991630916319163291633916349163591636916379163891639916409164191642916439164491645916469164791648916499165091651916529165391654916559165691657916589165991660916619166291663916649166591666916679166891669916709167191672916739167491675916769167791678916799168091681916829168391684916859168691687916889168991690916919169291693916949169591696916979169891699917009170191702917039170491705917069170791708917099171091711917129171391714917159171691717917189171991720917219172291723917249172591726917279172891729917309173191732917339173491735917369173791738917399174091741917429174391744917459174691747917489174991750917519175291753917549175591756917579175891759917609176191762917639176491765917669176791768917699177091771917729177391774917759177691777917789177991780917819178291783917849178591786917879178891789917909179191792917939179491795917969179791798917999180091801918029180391804918059180691807918089180991810918119181291813918149181591816918179181891819918209182191822918239182491825918269182791828918299183091831918329183391834918359183691837918389183991840918419184291843918449184591846918479184891849918509185191852918539185491855918569185791858918599186091861918629186391864918659186691867918689186991870918719187291873918749187591876918779187891879918809188191882918839188491885918869188791888918899189091891918929189391894918959189691897918989189991900919019190291903919049190591906919079190891909919109191191912919139191491915919169191791918919199192091921919229192391924919259192691927919289192991930919319193291933919349193591936919379193891939919409194191942919439194491945919469194791948919499195091951919529195391954919559195691957919589195991960919619196291963919649196591966919679196891969919709197191972919739197491975919769197791978919799198091981919829198391984919859198691987919889198991990919919199291993919949199591996919979199891999920009200192002920039200492005920069200792008920099201092011920129201392014920159201692017920189201992020920219202292023920249202592026920279202892029920309203192032920339203492035920369203792038920399204092041920429204392044920459204692047920489204992050920519205292053920549205592056920579205892059920609206192062920639206492065920669206792068920699207092071920729207392074920759207692077920789207992080920819208292083920849208592086920879208892089920909209192092920939209492095920969209792098920999210092101921029210392104921059210692107921089210992110921119211292113921149211592116921179211892119921209212192122921239212492125921269212792128921299213092131921329213392134921359213692137921389213992140921419214292143921449214592146921479214892149921509215192152921539215492155921569215792158921599216092161921629216392164921659216692167921689216992170921719217292173921749217592176921779217892179921809218192182921839218492185921869218792188921899219092191921929219392194921959219692197921989219992200922019220292203922049220592206922079220892209922109221192212922139221492215922169221792218922199222092221922229222392224922259222692227922289222992230922319223292233922349223592236922379223892239922409224192242922439224492245922469224792248922499225092251922529225392254922559225692257922589225992260922619226292263922649226592266922679226892269922709227192272922739227492275922769227792278922799228092281922829228392284922859228692287922889228992290922919229292293922949229592296922979229892299923009230192302923039230492305923069230792308923099231092311923129231392314923159231692317923189231992320923219232292323923249232592326923279232892329923309233192332923339233492335923369233792338923399234092341923429234392344923459234692347923489234992350923519235292353923549235592356923579235892359923609236192362923639236492365923669236792368923699237092371923729237392374923759237692377923789237992380923819238292383923849238592386923879238892389923909239192392923939239492395923969239792398923999240092401924029240392404924059240692407924089240992410924119241292413924149241592416924179241892419924209242192422924239242492425924269242792428924299243092431924329243392434924359243692437924389243992440924419244292443924449244592446924479244892449924509245192452924539245492455924569245792458924599246092461924629246392464924659246692467924689246992470924719247292473924749247592476924779247892479924809248192482924839248492485924869248792488924899249092491924929249392494924959249692497924989249992500925019250292503925049250592506925079250892509925109251192512925139251492515925169251792518925199252092521925229252392524925259252692527925289252992530925319253292533925349253592536925379253892539925409254192542925439254492545925469254792548925499255092551925529255392554925559255692557925589255992560925619256292563925649256592566925679256892569925709257192572925739257492575925769257792578925799258092581925829258392584925859258692587925889258992590925919259292593925949259592596925979259892599926009260192602926039260492605926069260792608926099261092611926129261392614926159261692617926189261992620926219262292623926249262592626926279262892629926309263192632926339263492635926369263792638926399264092641926429264392644926459264692647926489264992650926519265292653926549265592656926579265892659926609266192662926639266492665926669266792668926699267092671926729267392674926759267692677926789267992680926819268292683926849268592686926879268892689926909269192692926939269492695926969269792698926999270092701927029270392704927059270692707927089270992710927119271292713927149271592716927179271892719927209272192722927239272492725927269272792728927299273092731927329273392734927359273692737927389273992740927419274292743927449274592746927479274892749927509275192752927539275492755927569275792758927599276092761927629276392764927659276692767927689276992770927719277292773927749277592776927779277892779927809278192782927839278492785927869278792788927899279092791927929279392794927959279692797927989279992800928019280292803928049280592806928079280892809928109281192812928139281492815928169281792818928199282092821928229282392824928259282692827928289282992830928319283292833928349283592836928379283892839928409284192842928439284492845928469284792848928499285092851928529285392854928559285692857928589285992860928619286292863928649286592866928679286892869928709287192872928739287492875928769287792878928799288092881928829288392884928859288692887928889288992890928919289292893928949289592896928979289892899929009290192902929039290492905929069290792908929099291092911929129291392914929159291692917929189291992920929219292292923929249292592926929279292892929929309293192932929339293492935929369293792938929399294092941929429294392944929459294692947929489294992950929519295292953929549295592956929579295892959929609296192962929639296492965929669296792968929699297092971929729297392974929759297692977929789297992980929819298292983929849298592986929879298892989929909299192992929939299492995929969299792998929999300093001930029300393004930059300693007930089300993010930119301293013930149301593016930179301893019930209302193022930239302493025930269302793028930299303093031930329303393034930359303693037930389303993040930419304293043930449304593046930479304893049930509305193052930539305493055930569305793058930599306093061930629306393064930659306693067930689306993070930719307293073930749307593076930779307893079930809308193082930839308493085930869308793088930899309093091930929309393094930959309693097930989309993100931019310293103931049310593106931079310893109931109311193112931139311493115931169311793118931199312093121931229312393124931259312693127931289312993130931319313293133931349313593136931379313893139931409314193142931439314493145931469314793148931499315093151931529315393154931559315693157931589315993160931619316293163931649316593166931679316893169931709317193172931739317493175931769317793178931799318093181931829318393184931859318693187931889318993190931919319293193931949319593196931979319893199932009320193202932039320493205932069320793208932099321093211932129321393214932159321693217932189321993220932219322293223932249322593226932279322893229932309323193232932339323493235932369323793238932399324093241932429324393244932459324693247932489324993250932519325293253932549325593256932579325893259932609326193262932639326493265932669326793268932699327093271932729327393274932759327693277932789327993280932819328293283932849328593286932879328893289932909329193292932939329493295932969329793298932999330093301933029330393304933059330693307933089330993310933119331293313933149331593316933179331893319933209332193322933239332493325933269332793328933299333093331933329333393334933359333693337933389333993340933419334293343933449334593346933479334893349933509335193352933539335493355933569335793358933599336093361933629336393364933659336693367933689336993370933719337293373933749337593376933779337893379933809338193382933839338493385933869338793388933899339093391933929339393394933959339693397933989339993400934019340293403934049340593406934079340893409934109341193412934139341493415934169341793418934199342093421934229342393424934259342693427934289342993430934319343293433934349343593436934379343893439934409344193442934439344493445934469344793448934499345093451934529345393454934559345693457934589345993460934619346293463934649346593466934679346893469934709347193472934739347493475934769347793478934799348093481934829348393484934859348693487934889348993490934919349293493934949349593496934979349893499935009350193502935039350493505935069350793508935099351093511935129351393514935159351693517935189351993520935219352293523935249352593526935279352893529935309353193532935339353493535935369353793538935399354093541935429354393544935459354693547935489354993550935519355293553935549355593556935579355893559935609356193562935639356493565935669356793568935699357093571935729357393574935759357693577935789357993580935819358293583935849358593586935879358893589935909359193592935939359493595935969359793598935999360093601936029360393604936059360693607936089360993610936119361293613936149361593616936179361893619936209362193622936239362493625936269362793628936299363093631936329363393634936359363693637936389363993640936419364293643936449364593646936479364893649936509365193652936539365493655936569365793658936599366093661936629366393664936659366693667936689366993670936719367293673936749367593676936779367893679936809368193682936839368493685936869368793688936899369093691936929369393694936959369693697936989369993700937019370293703937049370593706937079370893709937109371193712937139371493715937169371793718937199372093721937229372393724937259372693727937289372993730937319373293733937349373593736937379373893739937409374193742937439374493745937469374793748937499375093751937529375393754937559375693757937589375993760937619376293763937649376593766937679376893769937709377193772937739377493775937769377793778937799378093781937829378393784937859378693787937889378993790937919379293793937949379593796937979379893799938009380193802938039380493805938069380793808938099381093811938129381393814938159381693817938189381993820938219382293823938249382593826938279382893829938309383193832938339383493835938369383793838938399384093841938429384393844938459384693847938489384993850938519385293853938549385593856938579385893859938609386193862938639386493865938669386793868938699387093871938729387393874938759387693877938789387993880938819388293883938849388593886938879388893889938909389193892938939389493895938969389793898938999390093901939029390393904939059390693907939089390993910939119391293913939149391593916939179391893919939209392193922939239392493925939269392793928939299393093931939329393393934939359393693937939389393993940939419394293943939449394593946939479394893949939509395193952939539395493955939569395793958939599396093961939629396393964939659396693967939689396993970939719397293973939749397593976939779397893979939809398193982939839398493985939869398793988939899399093991939929399393994939959399693997939989399994000940019400294003940049400594006940079400894009940109401194012940139401494015940169401794018940199402094021940229402394024940259402694027940289402994030940319403294033940349403594036940379403894039940409404194042940439404494045940469404794048940499405094051940529405394054940559405694057940589405994060940619406294063940649406594066940679406894069940709407194072940739407494075940769407794078940799408094081940829408394084940859408694087940889408994090940919409294093940949409594096940979409894099941009410194102941039410494105941069410794108941099411094111941129411394114941159411694117941189411994120941219412294123941249412594126941279412894129941309413194132941339413494135941369413794138941399414094141941429414394144941459414694147941489414994150941519415294153941549415594156941579415894159941609416194162941639416494165941669416794168941699417094171941729417394174941759417694177941789417994180941819418294183941849418594186941879418894189941909419194192941939419494195941969419794198941999420094201942029420394204942059420694207942089420994210942119421294213942149421594216942179421894219942209422194222942239422494225942269422794228942299423094231942329423394234942359423694237942389423994240942419424294243942449424594246942479424894249942509425194252942539425494255942569425794258942599426094261942629426394264942659426694267942689426994270942719427294273942749427594276942779427894279942809428194282942839428494285942869428794288942899429094291942929429394294942959429694297942989429994300943019430294303943049430594306943079430894309943109431194312943139431494315943169431794318943199432094321943229432394324943259432694327943289432994330943319433294333943349433594336943379433894339943409434194342943439434494345943469434794348943499435094351943529435394354943559435694357943589435994360943619436294363943649436594366943679436894369943709437194372943739437494375943769437794378943799438094381943829438394384943859438694387943889438994390943919439294393943949439594396943979439894399944009440194402944039440494405944069440794408944099441094411944129441394414944159441694417944189441994420944219442294423944249442594426944279442894429944309443194432944339443494435944369443794438944399444094441944429444394444944459444694447944489444994450944519445294453944549445594456944579445894459944609446194462944639446494465944669446794468944699447094471944729447394474944759447694477944789447994480944819448294483944849448594486944879448894489944909449194492944939449494495944969449794498944999450094501945029450394504945059450694507945089450994510945119451294513945149451594516945179451894519945209452194522945239452494525945269452794528945299453094531945329453394534945359453694537945389453994540945419454294543945449454594546945479454894549945509455194552945539455494555945569455794558945599456094561945629456394564945659456694567945689456994570945719457294573945749457594576945779457894579945809458194582945839458494585945869458794588945899459094591945929459394594945959459694597945989459994600946019460294603946049460594606946079460894609946109461194612946139461494615946169461794618946199462094621946229462394624946259462694627946289462994630946319463294633946349463594636946379463894639946409464194642946439464494645946469464794648946499465094651946529465394654946559465694657946589465994660946619466294663946649466594666946679466894669946709467194672946739467494675946769467794678946799468094681946829468394684946859468694687946889468994690946919469294693946949469594696946979469894699947009470194702947039470494705947069470794708947099471094711947129471394714947159471694717947189471994720947219472294723947249472594726947279472894729947309473194732947339473494735947369473794738947399474094741947429474394744947459474694747947489474994750947519475294753947549475594756947579475894759947609476194762947639476494765947669476794768947699477094771947729477394774947759477694777947789477994780947819478294783947849478594786947879478894789947909479194792947939479494795947969479794798947999480094801948029480394804948059480694807948089480994810948119481294813948149481594816948179481894819948209482194822948239482494825948269482794828948299483094831948329483394834948359483694837948389483994840948419484294843948449484594846948479484894849948509485194852948539485494855948569485794858948599486094861948629486394864948659486694867948689486994870948719487294873948749487594876948779487894879948809488194882948839488494885948869488794888948899489094891948929489394894948959489694897948989489994900949019490294903949049490594906949079490894909949109491194912949139491494915949169491794918949199492094921949229492394924949259492694927949289492994930949319493294933949349493594936949379493894939949409494194942949439494494945949469494794948949499495094951949529495394954949559495694957949589495994960949619496294963949649496594966949679496894969949709497194972949739497494975949769497794978949799498094981949829498394984949859498694987949889498994990949919499294993949949499594996949979499894999950009500195002950039500495005950069500795008950099501095011950129501395014950159501695017950189501995020950219502295023950249502595026950279502895029950309503195032950339503495035950369503795038950399504095041950429504395044950459504695047950489504995050950519505295053950549505595056950579505895059950609506195062950639506495065950669506795068950699507095071950729507395074950759507695077950789507995080950819508295083950849508595086950879508895089950909509195092950939509495095950969509795098950999510095101951029510395104951059510695107951089510995110951119511295113951149511595116951179511895119951209512195122951239512495125951269512795128951299513095131951329513395134951359513695137951389513995140951419514295143951449514595146951479514895149951509515195152951539515495155951569515795158951599516095161951629516395164951659516695167951689516995170951719517295173951749517595176951779517895179951809518195182951839518495185951869518795188951899519095191951929519395194951959519695197951989519995200952019520295203952049520595206952079520895209952109521195212952139521495215952169521795218952199522095221952229522395224952259522695227952289522995230952319523295233952349523595236952379523895239952409524195242952439524495245952469524795248952499525095251952529525395254952559525695257952589525995260952619526295263952649526595266952679526895269952709527195272952739527495275952769527795278952799528095281952829528395284952859528695287952889528995290952919529295293952949529595296952979529895299953009530195302953039530495305953069530795308953099531095311953129531395314953159531695317953189531995320953219532295323953249532595326953279532895329953309533195332953339533495335953369533795338953399534095341953429534395344953459534695347953489534995350953519535295353953549535595356953579535895359953609536195362953639536495365953669536795368953699537095371953729537395374953759537695377953789537995380953819538295383953849538595386953879538895389953909539195392953939539495395953969539795398953999540095401954029540395404954059540695407954089540995410954119541295413954149541595416954179541895419954209542195422954239542495425954269542795428954299543095431954329543395434954359543695437954389543995440954419544295443954449544595446954479544895449954509545195452954539545495455954569545795458954599546095461954629546395464954659546695467954689546995470954719547295473954749547595476954779547895479954809548195482954839548495485954869548795488954899549095491954929549395494954959549695497954989549995500955019550295503955049550595506955079550895509955109551195512955139551495515955169551795518955199552095521955229552395524955259552695527955289552995530955319553295533955349553595536955379553895539955409554195542955439554495545955469554795548955499555095551955529555395554955559555695557955589555995560955619556295563955649556595566955679556895569955709557195572955739557495575955769557795578955799558095581955829558395584955859558695587955889558995590955919559295593955949559595596955979559895599956009560195602956039560495605956069560795608956099561095611956129561395614956159561695617956189561995620956219562295623956249562595626956279562895629956309563195632956339563495635956369563795638956399564095641956429564395644956459564695647956489564995650956519565295653956549565595656956579565895659956609566195662956639566495665956669566795668956699567095671956729567395674956759567695677956789567995680956819568295683956849568595686956879568895689956909569195692956939569495695956969569795698956999570095701957029570395704957059570695707957089570995710957119571295713957149571595716957179571895719957209572195722957239572495725957269572795728957299573095731957329573395734957359573695737957389573995740957419574295743957449574595746957479574895749957509575195752957539575495755957569575795758957599576095761957629576395764957659576695767957689576995770957719577295773957749577595776957779577895779957809578195782957839578495785957869578795788957899579095791957929579395794957959579695797957989579995800958019580295803958049580595806958079580895809958109581195812958139581495815958169581795818958199582095821958229582395824958259582695827958289582995830958319583295833958349583595836958379583895839958409584195842958439584495845958469584795848958499585095851958529585395854958559585695857958589585995860958619586295863958649586595866958679586895869958709587195872958739587495875958769587795878958799588095881958829588395884958859588695887958889588995890958919589295893958949589595896958979589895899959009590195902959039590495905959069590795908959099591095911959129591395914959159591695917959189591995920959219592295923959249592595926959279592895929959309593195932959339593495935959369593795938959399594095941959429594395944959459594695947959489594995950959519595295953959549595595956959579595895959959609596195962959639596495965959669596795968959699597095971959729597395974959759597695977959789597995980959819598295983959849598595986959879598895989959909599195992959939599495995959969599795998959999600096001960029600396004960059600696007960089600996010960119601296013960149601596016960179601896019960209602196022960239602496025960269602796028960299603096031960329603396034960359603696037960389603996040960419604296043960449604596046960479604896049960509605196052960539605496055960569605796058960599606096061960629606396064960659606696067960689606996070960719607296073960749607596076960779607896079960809608196082960839608496085960869608796088960899609096091960929609396094960959609696097960989609996100961019610296103961049610596106961079610896109961109611196112961139611496115961169611796118961199612096121961229612396124961259612696127961289612996130961319613296133961349613596136961379613896139961409614196142961439614496145961469614796148961499615096151961529615396154961559615696157961589615996160961619616296163961649616596166961679616896169961709617196172961739617496175961769617796178961799618096181961829618396184961859618696187961889618996190961919619296193961949619596196961979619896199962009620196202962039620496205962069620796208962099621096211962129621396214962159621696217962189621996220962219622296223962249622596226962279622896229962309623196232962339623496235962369623796238962399624096241962429624396244962459624696247962489624996250962519625296253962549625596256962579625896259962609626196262962639626496265962669626796268962699627096271962729627396274962759627696277962789627996280962819628296283962849628596286962879628896289962909629196292962939629496295962969629796298962999630096301963029630396304963059630696307963089630996310963119631296313963149631596316963179631896319963209632196322963239632496325963269632796328963299633096331963329633396334963359633696337963389633996340963419634296343963449634596346963479634896349963509635196352963539635496355963569635796358963599636096361963629636396364963659636696367963689636996370963719637296373963749637596376963779637896379963809638196382963839638496385963869638796388963899639096391963929639396394963959639696397963989639996400964019640296403964049640596406964079640896409964109641196412964139641496415964169641796418964199642096421964229642396424964259642696427964289642996430964319643296433964349643596436964379643896439964409644196442964439644496445964469644796448964499645096451964529645396454964559645696457964589645996460964619646296463964649646596466964679646896469964709647196472964739647496475964769647796478964799648096481964829648396484964859648696487964889648996490964919649296493964949649596496964979649896499965009650196502965039650496505965069650796508965099651096511965129651396514965159651696517965189651996520965219652296523965249652596526965279652896529965309653196532965339653496535965369653796538965399654096541965429654396544965459654696547965489654996550965519655296553965549655596556965579655896559965609656196562965639656496565965669656796568965699657096571965729657396574965759657696577965789657996580965819658296583965849658596586965879658896589965909659196592965939659496595965969659796598965999660096601966029660396604966059660696607966089660996610966119661296613966149661596616966179661896619966209662196622966239662496625966269662796628966299663096631966329663396634966359663696637966389663996640966419664296643966449664596646966479664896649966509665196652966539665496655966569665796658966599666096661966629666396664966659666696667966689666996670966719667296673966749667596676966779667896679966809668196682966839668496685966869668796688966899669096691966929669396694966959669696697966989669996700967019670296703967049670596706967079670896709967109671196712967139671496715967169671796718967199672096721967229672396724967259672696727967289672996730967319673296733967349673596736967379673896739967409674196742967439674496745967469674796748967499675096751967529675396754967559675696757967589675996760967619676296763967649676596766967679676896769967709677196772967739677496775967769677796778967799678096781967829678396784967859678696787967889678996790967919679296793967949679596796967979679896799968009680196802968039680496805968069680796808968099681096811968129681396814968159681696817968189681996820968219682296823968249682596826968279682896829968309683196832968339683496835968369683796838968399684096841968429684396844968459684696847968489684996850968519685296853968549685596856968579685896859968609686196862968639686496865968669686796868968699687096871968729687396874968759687696877968789687996880968819688296883968849688596886968879688896889968909689196892968939689496895968969689796898968999690096901969029690396904969059690696907969089690996910969119691296913969149691596916969179691896919969209692196922969239692496925969269692796928969299693096931969329693396934969359693696937969389693996940969419694296943969449694596946969479694896949969509695196952969539695496955969569695796958969599696096961969629696396964969659696696967969689696996970969719697296973969749697596976969779697896979969809698196982969839698496985969869698796988969899699096991969929699396994969959699696997969989699997000970019700297003970049700597006970079700897009970109701197012970139701497015970169701797018970199702097021970229702397024970259702697027970289702997030970319703297033970349703597036970379703897039970409704197042970439704497045970469704797048970499705097051970529705397054970559705697057970589705997060970619706297063970649706597066970679706897069970709707197072970739707497075970769707797078970799708097081970829708397084970859708697087970889708997090970919709297093970949709597096970979709897099971009710197102971039710497105971069710797108971099711097111971129711397114971159711697117971189711997120971219712297123971249712597126971279712897129971309713197132971339713497135971369713797138971399714097141971429714397144971459714697147971489714997150971519715297153971549715597156971579715897159971609716197162971639716497165971669716797168971699717097171971729717397174971759717697177971789717997180971819718297183971849718597186971879718897189971909719197192971939719497195971969719797198971999720097201972029720397204972059720697207972089720997210972119721297213972149721597216972179721897219972209722197222972239722497225972269722797228972299723097231972329723397234972359723697237972389723997240972419724297243972449724597246972479724897249972509725197252972539725497255972569725797258972599726097261972629726397264972659726697267972689726997270972719727297273972749727597276972779727897279972809728197282972839728497285972869728797288972899729097291972929729397294972959729697297972989729997300973019730297303973049730597306973079730897309973109731197312973139731497315973169731797318973199732097321973229732397324973259732697327973289732997330973319733297333973349733597336973379733897339973409734197342973439734497345973469734797348973499735097351973529735397354973559735697357973589735997360973619736297363973649736597366973679736897369973709737197372973739737497375973769737797378973799738097381973829738397384973859738697387973889738997390973919739297393973949739597396973979739897399974009740197402974039740497405974069740797408974099741097411974129741397414974159741697417974189741997420974219742297423974249742597426974279742897429974309743197432974339743497435974369743797438974399744097441974429744397444974459744697447974489744997450974519745297453974549745597456974579745897459974609746197462974639746497465974669746797468974699747097471974729747397474974759747697477974789747997480974819748297483974849748597486974879748897489974909749197492974939749497495974969749797498974999750097501975029750397504975059750697507975089750997510975119751297513975149751597516975179751897519975209752197522975239752497525975269752797528975299753097531975329753397534975359753697537975389753997540975419754297543975449754597546975479754897549975509755197552975539755497555975569755797558975599756097561975629756397564975659756697567975689756997570975719757297573975749757597576975779757897579975809758197582975839758497585975869758797588975899759097591975929759397594975959759697597975989759997600976019760297603976049760597606976079760897609976109761197612976139761497615976169761797618976199762097621976229762397624976259762697627976289762997630976319763297633976349763597636976379763897639976409764197642976439764497645976469764797648976499765097651976529765397654976559765697657976589765997660976619766297663976649766597666976679766897669976709767197672976739767497675976769767797678976799768097681976829768397684976859768697687976889768997690976919769297693976949769597696976979769897699977009770197702977039770497705977069770797708977099771097711977129771397714977159771697717977189771997720977219772297723977249772597726977279772897729977309773197732977339773497735977369773797738977399774097741977429774397744977459774697747977489774997750977519775297753977549775597756977579775897759977609776197762977639776497765977669776797768977699777097771977729777397774977759777697777977789777997780977819778297783977849778597786977879778897789977909779197792977939779497795977969779797798977999780097801978029780397804978059780697807978089780997810978119781297813978149781597816978179781897819978209782197822978239782497825978269782797828978299783097831978329783397834978359783697837978389783997840978419784297843978449784597846978479784897849978509785197852978539785497855978569785797858978599786097861978629786397864978659786697867978689786997870978719787297873978749787597876978779787897879978809788197882978839788497885978869788797888978899789097891978929789397894978959789697897978989789997900979019790297903979049790597906979079790897909979109791197912979139791497915979169791797918979199792097921979229792397924979259792697927979289792997930979319793297933979349793597936979379793897939979409794197942979439794497945979469794797948979499795097951979529795397954979559795697957979589795997960979619796297963979649796597966979679796897969979709797197972979739797497975979769797797978979799798097981979829798397984979859798697987979889798997990979919799297993979949799597996979979799897999980009800198002980039800498005980069800798008980099801098011980129801398014980159801698017980189801998020980219802298023980249802598026980279802898029980309803198032980339803498035980369803798038980399804098041980429804398044980459804698047980489804998050980519805298053980549805598056980579805898059980609806198062980639806498065980669806798068980699807098071980729807398074980759807698077980789807998080980819808298083980849808598086980879808898089980909809198092980939809498095980969809798098980999810098101981029810398104981059810698107981089810998110981119811298113981149811598116981179811898119981209812198122981239812498125981269812798128981299813098131981329813398134981359813698137981389813998140981419814298143981449814598146981479814898149981509815198152981539815498155981569815798158981599816098161981629816398164981659816698167981689816998170981719817298173981749817598176981779817898179981809818198182981839818498185981869818798188981899819098191981929819398194981959819698197981989819998200982019820298203982049820598206982079820898209982109821198212982139821498215982169821798218982199822098221982229822398224982259822698227982289822998230982319823298233982349823598236982379823898239982409824198242982439824498245982469824798248982499825098251982529825398254982559825698257982589825998260982619826298263982649826598266982679826898269982709827198272982739827498275982769827798278982799828098281982829828398284982859828698287982889828998290982919829298293982949829598296982979829898299983009830198302983039830498305983069830798308983099831098311983129831398314983159831698317983189831998320983219832298323983249832598326983279832898329983309833198332983339833498335983369833798338983399834098341983429834398344983459834698347983489834998350983519835298353983549835598356983579835898359983609836198362983639836498365983669836798368983699837098371983729837398374983759837698377983789837998380983819838298383983849838598386983879838898389983909839198392983939839498395983969839798398983999840098401984029840398404984059840698407984089840998410
  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. _this.skipOnPointerObservable = false;
  1342. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1343. return _this;
  1344. }
  1345. return PointerInfoPre;
  1346. }(PointerInfoBase));
  1347. BABYLON.PointerInfoPre = PointerInfoPre;
  1348. /**
  1349. * This type contains all the data related to a pointer event in Babylon.js.
  1350. * 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.
  1351. */
  1352. var PointerInfo = /** @class */ (function (_super) {
  1353. __extends(PointerInfo, _super);
  1354. function PointerInfo(type, event, pickInfo) {
  1355. var _this = _super.call(this, type, event) || this;
  1356. _this.pickInfo = pickInfo;
  1357. return _this;
  1358. }
  1359. return PointerInfo;
  1360. }(PointerInfoBase));
  1361. BABYLON.PointerInfo = PointerInfo;
  1362. })(BABYLON || (BABYLON = {}));
  1363. //# sourceMappingURL=babylon.pointerEvents.js.map
  1364. var BABYLON;
  1365. (function (BABYLON) {
  1366. BABYLON.ToGammaSpace = 1 / 2.2;
  1367. BABYLON.ToLinearSpace = 2.2;
  1368. BABYLON.Epsilon = 0.001;
  1369. /**
  1370. * Class used to hold a RBG color
  1371. */
  1372. var Color3 = /** @class */ (function () {
  1373. /**
  1374. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1375. * @param r defines the red component (between 0 and 1, default is 0)
  1376. * @param g defines the green component (between 0 and 1, default is 0)
  1377. * @param b defines the blue component (between 0 and 1, default is 0)
  1378. */
  1379. function Color3(
  1380. /**
  1381. * Defines the red component (between 0 and 1, default is 0)
  1382. */
  1383. r,
  1384. /**
  1385. * Defines the green component (between 0 and 1, default is 0)
  1386. */
  1387. g,
  1388. /**
  1389. * Defines the blue component (between 0 and 1, default is 0)
  1390. */
  1391. b) {
  1392. if (r === void 0) { r = 0; }
  1393. if (g === void 0) { g = 0; }
  1394. if (b === void 0) { b = 0; }
  1395. this.r = r;
  1396. this.g = g;
  1397. this.b = b;
  1398. }
  1399. /**
  1400. * Creates a string with the Color3 current values
  1401. * @returns the string representation of the Color3 object
  1402. */
  1403. Color3.prototype.toString = function () {
  1404. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1405. };
  1406. /**
  1407. * Returns the string "Color3"
  1408. * @returns "Color3"
  1409. */
  1410. Color3.prototype.getClassName = function () {
  1411. return "Color3";
  1412. };
  1413. /**
  1414. * Compute the Color3 hash code
  1415. * @returns an unique number that can be used to hash Color3 objects
  1416. */
  1417. Color3.prototype.getHashCode = function () {
  1418. var hash = this.r || 0;
  1419. hash = (hash * 397) ^ (this.g || 0);
  1420. hash = (hash * 397) ^ (this.b || 0);
  1421. return hash;
  1422. };
  1423. // Operators
  1424. /**
  1425. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1426. * @param array defines the array where to store the r,g,b components
  1427. * @param index defines an optional index in the target array to define where to start storing values
  1428. * @returns the current Color3 object
  1429. */
  1430. Color3.prototype.toArray = function (array, index) {
  1431. if (index === undefined) {
  1432. index = 0;
  1433. }
  1434. array[index] = this.r;
  1435. array[index + 1] = this.g;
  1436. array[index + 2] = this.b;
  1437. return this;
  1438. };
  1439. /**
  1440. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1441. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1442. * @returns a new {BABYLON.Color4} object
  1443. */
  1444. Color3.prototype.toColor4 = function (alpha) {
  1445. if (alpha === void 0) { alpha = 1; }
  1446. return new Color4(this.r, this.g, this.b, alpha);
  1447. };
  1448. /**
  1449. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1450. * @returns the new array
  1451. */
  1452. Color3.prototype.asArray = function () {
  1453. var result = new Array();
  1454. this.toArray(result, 0);
  1455. return result;
  1456. };
  1457. /**
  1458. * Returns the luminance value
  1459. * @returns a float value
  1460. */
  1461. Color3.prototype.toLuminance = function () {
  1462. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1463. };
  1464. /**
  1465. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1466. * @param otherColor defines the second operand
  1467. * @returns the new Color3 object
  1468. */
  1469. Color3.prototype.multiply = function (otherColor) {
  1470. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1471. };
  1472. /**
  1473. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1474. * @param otherColor defines the second operand
  1475. * @param result defines the Color3 object where to store the result
  1476. * @returns the current Color3
  1477. */
  1478. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1479. result.r = this.r * otherColor.r;
  1480. result.g = this.g * otherColor.g;
  1481. result.b = this.b * otherColor.b;
  1482. return this;
  1483. };
  1484. /**
  1485. * Determines equality between Color3 objects
  1486. * @param otherColor defines the second operand
  1487. * @returns true if the rgb values are equal to the given ones
  1488. */
  1489. Color3.prototype.equals = function (otherColor) {
  1490. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1491. };
  1492. /**
  1493. * Determines equality between the current Color3 object and a set of r,b,g values
  1494. * @param r defines the red component to check
  1495. * @param g defines the green component to check
  1496. * @param b defines the blue component to check
  1497. * @returns true if the rgb values are equal to the given ones
  1498. */
  1499. Color3.prototype.equalsFloats = function (r, g, b) {
  1500. return this.r === r && this.g === g && this.b === b;
  1501. };
  1502. /**
  1503. * Multiplies in place each rgb value by scale
  1504. * @param scale defines the scaling factor
  1505. * @returns the updated Color3
  1506. */
  1507. Color3.prototype.scale = function (scale) {
  1508. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1509. };
  1510. /**
  1511. * Multiplies the rgb values by scale and stores the result into "result"
  1512. * @param scale defines the scaling factor
  1513. * @param result defines the Color3 object where to store the result
  1514. * @returns the unmodified current Color3
  1515. */
  1516. Color3.prototype.scaleToRef = function (scale, result) {
  1517. result.r = this.r * scale;
  1518. result.g = this.g * scale;
  1519. result.b = this.b * scale;
  1520. return this;
  1521. };
  1522. /**
  1523. * Scale the current Color3 values by a factor and add the result to a given Color3
  1524. * @param scale defines the scale factor
  1525. * @param result defines color to store the result into
  1526. * @returns the unmodified current Color3
  1527. */
  1528. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1529. result.r += this.r * scale;
  1530. result.g += this.g * scale;
  1531. result.b += this.b * scale;
  1532. return this;
  1533. };
  1534. /**
  1535. * Clamps the rgb values by the min and max values and stores the result into "result"
  1536. * @param min defines minimum clamping value (default is 0)
  1537. * @param max defines maximum clamping value (default is 1)
  1538. * @param result defines color to store the result into
  1539. * @returns the original Color3
  1540. */
  1541. Color3.prototype.clampToRef = function (min, max, result) {
  1542. if (min === void 0) { min = 0; }
  1543. if (max === void 0) { max = 1; }
  1544. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1545. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1546. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1547. return this;
  1548. };
  1549. /**
  1550. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1551. * @param otherColor defines the second operand
  1552. * @returns the new Color3
  1553. */
  1554. Color3.prototype.add = function (otherColor) {
  1555. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1556. };
  1557. /**
  1558. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1559. * @param otherColor defines the second operand
  1560. * @param result defines Color3 object to store the result into
  1561. * @returns the unmodified current Color3
  1562. */
  1563. Color3.prototype.addToRef = function (otherColor, result) {
  1564. result.r = this.r + otherColor.r;
  1565. result.g = this.g + otherColor.g;
  1566. result.b = this.b + otherColor.b;
  1567. return this;
  1568. };
  1569. /**
  1570. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1571. * @param otherColor defines the second operand
  1572. * @returns the new Color3
  1573. */
  1574. Color3.prototype.subtract = function (otherColor) {
  1575. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1576. };
  1577. /**
  1578. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1579. * @param otherColor defines the second operand
  1580. * @param result defines Color3 object to store the result into
  1581. * @returns the unmodified current Color3
  1582. */
  1583. Color3.prototype.subtractToRef = function (otherColor, result) {
  1584. result.r = this.r - otherColor.r;
  1585. result.g = this.g - otherColor.g;
  1586. result.b = this.b - otherColor.b;
  1587. return this;
  1588. };
  1589. /**
  1590. * Copy the current object
  1591. * @returns a new Color3 copied the current one
  1592. */
  1593. Color3.prototype.clone = function () {
  1594. return new Color3(this.r, this.g, this.b);
  1595. };
  1596. /**
  1597. * Copies the rgb values from the source in the current Color3
  1598. * @param source defines the source Color3 object
  1599. * @returns the updated Color3 object
  1600. */
  1601. Color3.prototype.copyFrom = function (source) {
  1602. this.r = source.r;
  1603. this.g = source.g;
  1604. this.b = source.b;
  1605. return this;
  1606. };
  1607. /**
  1608. * Updates the Color3 rgb values from the given floats
  1609. * @param r defines the red component to read from
  1610. * @param g defines the green component to read from
  1611. * @param b defines the blue component to read from
  1612. * @returns the current Color3 object
  1613. */
  1614. Color3.prototype.copyFromFloats = function (r, g, b) {
  1615. this.r = r;
  1616. this.g = g;
  1617. this.b = b;
  1618. return this;
  1619. };
  1620. /**
  1621. * Updates the Color3 rgb values from the given floats
  1622. * @param r defines the red component to read from
  1623. * @param g defines the green component to read from
  1624. * @param b defines the blue component to read from
  1625. * @returns the current Color3 object
  1626. */
  1627. Color3.prototype.set = function (r, g, b) {
  1628. return this.copyFromFloats(r, g, b);
  1629. };
  1630. /**
  1631. * Compute the Color3 hexadecimal code as a string
  1632. * @returns a string containing the hexadecimal representation of the Color3 object
  1633. */
  1634. Color3.prototype.toHexString = function () {
  1635. var intR = (this.r * 255) | 0;
  1636. var intG = (this.g * 255) | 0;
  1637. var intB = (this.b * 255) | 0;
  1638. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1639. };
  1640. /**
  1641. * Computes a new Color3 converted from the current one to linear space
  1642. * @returns a new Color3 object
  1643. */
  1644. Color3.prototype.toLinearSpace = function () {
  1645. var convertedColor = new Color3();
  1646. this.toLinearSpaceToRef(convertedColor);
  1647. return convertedColor;
  1648. };
  1649. /**
  1650. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1651. * @param convertedColor defines the Color3 object where to store the linear space version
  1652. * @returns the unmodified Color3
  1653. */
  1654. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1655. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1656. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1657. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1658. return this;
  1659. };
  1660. /**
  1661. * Computes a new Color3 converted from the current one to gamma space
  1662. * @returns a new Color3 object
  1663. */
  1664. Color3.prototype.toGammaSpace = function () {
  1665. var convertedColor = new Color3();
  1666. this.toGammaSpaceToRef(convertedColor);
  1667. return convertedColor;
  1668. };
  1669. /**
  1670. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1671. * @param convertedColor defines the Color3 object where to store the gamma space version
  1672. * @returns the unmodified Color3
  1673. */
  1674. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1675. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1676. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1677. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1678. return this;
  1679. };
  1680. // Statics
  1681. /**
  1682. * Creates a new Color3 from the string containing valid hexadecimal values
  1683. * @param hex defines a string containing valid hexadecimal values
  1684. * @returns a new Color3 object
  1685. */
  1686. Color3.FromHexString = function (hex) {
  1687. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1688. return new Color3(0, 0, 0);
  1689. }
  1690. var r = parseInt(hex.substring(1, 3), 16);
  1691. var g = parseInt(hex.substring(3, 5), 16);
  1692. var b = parseInt(hex.substring(5, 7), 16);
  1693. return Color3.FromInts(r, g, b);
  1694. };
  1695. /**
  1696. * Creates a new Vector3 from the starting index of the given array
  1697. * @param array defines the source array
  1698. * @param offset defines an offset in the source array
  1699. * @returns a new Color3 object
  1700. */
  1701. Color3.FromArray = function (array, offset) {
  1702. if (offset === void 0) { offset = 0; }
  1703. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1704. };
  1705. /**
  1706. * Creates a new Color3 from integer values (< 256)
  1707. * @param r defines the red component to read from (value between 0 and 255)
  1708. * @param g defines the green component to read from (value between 0 and 255)
  1709. * @param b defines the blue component to read from (value between 0 and 255)
  1710. * @returns a new Color3 object
  1711. */
  1712. Color3.FromInts = function (r, g, b) {
  1713. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1714. };
  1715. /**
  1716. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1717. * @param start defines the start Color3 value
  1718. * @param end defines the end Color3 value
  1719. * @param amount defines the gradient value between start and end
  1720. * @returns a new Color3 object
  1721. */
  1722. Color3.Lerp = function (start, end, amount) {
  1723. var r = start.r + ((end.r - start.r) * amount);
  1724. var g = start.g + ((end.g - start.g) * amount);
  1725. var b = start.b + ((end.b - start.b) * amount);
  1726. return new Color3(r, g, b);
  1727. };
  1728. /**
  1729. * Returns a Color3 value containing a red color
  1730. * @returns a new Color3 object
  1731. */
  1732. Color3.Red = function () { return new Color3(1, 0, 0); };
  1733. /**
  1734. * Returns a Color3 value containing a green color
  1735. * @returns a new Color3 object
  1736. */
  1737. Color3.Green = function () { return new Color3(0, 1, 0); };
  1738. /**
  1739. * Returns a Color3 value containing a blue color
  1740. * @returns a new Color3 object
  1741. */
  1742. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1743. /**
  1744. * Returns a Color3 value containing a black color
  1745. * @returns a new Color3 object
  1746. */
  1747. Color3.Black = function () { return new Color3(0, 0, 0); };
  1748. /**
  1749. * Returns a Color3 value containing a white color
  1750. * @returns a new Color3 object
  1751. */
  1752. Color3.White = function () { return new Color3(1, 1, 1); };
  1753. /**
  1754. * Returns a Color3 value containing a purple color
  1755. * @returns a new Color3 object
  1756. */
  1757. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1758. /**
  1759. * Returns a Color3 value containing a magenta color
  1760. * @returns a new Color3 object
  1761. */
  1762. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1763. /**
  1764. * Returns a Color3 value containing a yellow color
  1765. * @returns a new Color3 object
  1766. */
  1767. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1768. /**
  1769. * Returns a Color3 value containing a gray color
  1770. * @returns a new Color3 object
  1771. */
  1772. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1773. /**
  1774. * Returns a Color3 value containing a teal color
  1775. * @returns a new Color3 object
  1776. */
  1777. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1778. /**
  1779. * Returns a Color3 value containing a random color
  1780. * @returns a new Color3 object
  1781. */
  1782. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1783. return Color3;
  1784. }());
  1785. BABYLON.Color3 = Color3;
  1786. /**
  1787. * Class used to hold a RBGA color
  1788. */
  1789. var Color4 = /** @class */ (function () {
  1790. /**
  1791. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1792. * @param r defines the red component (between 0 and 1, default is 0)
  1793. * @param g defines the green component (between 0 and 1, default is 0)
  1794. * @param b defines the blue component (between 0 and 1, default is 0)
  1795. * @param a defines the alpha component (between 0 and 1, default is 1)
  1796. */
  1797. function Color4(
  1798. /**
  1799. * Defines the red component (between 0 and 1, default is 0)
  1800. */
  1801. r,
  1802. /**
  1803. * Defines the green component (between 0 and 1, default is 0)
  1804. */
  1805. g,
  1806. /**
  1807. * Defines the blue component (between 0 and 1, default is 0)
  1808. */
  1809. b,
  1810. /**
  1811. * Defines the alpha component (between 0 and 1, default is 1)
  1812. */
  1813. a) {
  1814. if (r === void 0) { r = 0; }
  1815. if (g === void 0) { g = 0; }
  1816. if (b === void 0) { b = 0; }
  1817. if (a === void 0) { a = 1; }
  1818. this.r = r;
  1819. this.g = g;
  1820. this.b = b;
  1821. this.a = a;
  1822. }
  1823. // Operators
  1824. /**
  1825. * Adds in place the given Color4 values to the current Color4 object
  1826. * @param right defines the second operand
  1827. * @returns the current updated Color4 object
  1828. */
  1829. Color4.prototype.addInPlace = function (right) {
  1830. this.r += right.r;
  1831. this.g += right.g;
  1832. this.b += right.b;
  1833. this.a += right.a;
  1834. return this;
  1835. };
  1836. /**
  1837. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1838. * @returns the new array
  1839. */
  1840. Color4.prototype.asArray = function () {
  1841. var result = new Array();
  1842. this.toArray(result, 0);
  1843. return result;
  1844. };
  1845. /**
  1846. * Stores from the starting index in the given array the Color4 successive values
  1847. * @param array defines the array where to store the r,g,b components
  1848. * @param index defines an optional index in the target array to define where to start storing values
  1849. * @returns the current Color4 object
  1850. */
  1851. Color4.prototype.toArray = function (array, index) {
  1852. if (index === undefined) {
  1853. index = 0;
  1854. }
  1855. array[index] = this.r;
  1856. array[index + 1] = this.g;
  1857. array[index + 2] = this.b;
  1858. array[index + 3] = this.a;
  1859. return this;
  1860. };
  1861. /**
  1862. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1863. * @param right defines the second operand
  1864. * @returns a new Color4 object
  1865. */
  1866. Color4.prototype.add = function (right) {
  1867. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1868. };
  1869. /**
  1870. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1871. * @param right defines the second operand
  1872. * @returns a new Color4 object
  1873. */
  1874. Color4.prototype.subtract = function (right) {
  1875. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1876. };
  1877. /**
  1878. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1879. * @param right defines the second operand
  1880. * @param result defines the Color4 object where to store the result
  1881. * @returns the current Color4 object
  1882. */
  1883. Color4.prototype.subtractToRef = function (right, result) {
  1884. result.r = this.r - right.r;
  1885. result.g = this.g - right.g;
  1886. result.b = this.b - right.b;
  1887. result.a = this.a - right.a;
  1888. return this;
  1889. };
  1890. /**
  1891. * Creates a new Color4 with the current Color4 values multiplied by scale
  1892. * @param scale defines the scaling factor to apply
  1893. * @returns a new Color4 object
  1894. */
  1895. Color4.prototype.scale = function (scale) {
  1896. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  1897. };
  1898. /**
  1899. * Multiplies the current Color4 values by scale and stores the result in "result"
  1900. * @param scale defines the scaling factor to apply
  1901. * @param result defines the Color4 object where to store the result
  1902. * @returns the current unmodified Color4
  1903. */
  1904. Color4.prototype.scaleToRef = function (scale, result) {
  1905. result.r = this.r * scale;
  1906. result.g = this.g * scale;
  1907. result.b = this.b * scale;
  1908. result.a = this.a * scale;
  1909. return this;
  1910. };
  1911. /**
  1912. * Scale the current Color4 values by a factor and add the result to a given Color4
  1913. * @param scale defines the scale factor
  1914. * @param result defines the Color4 object where to store the result
  1915. * @returns the unmodified current Color4
  1916. */
  1917. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  1918. result.r += this.r * scale;
  1919. result.g += this.g * scale;
  1920. result.b += this.b * scale;
  1921. result.a += this.a * scale;
  1922. return this;
  1923. };
  1924. /**
  1925. * Clamps the rgb values by the min and max values and stores the result into "result"
  1926. * @param min defines minimum clamping value (default is 0)
  1927. * @param max defines maximum clamping value (default is 1)
  1928. * @param result defines color to store the result into.
  1929. * @returns the cuurent Color4
  1930. */
  1931. Color4.prototype.clampToRef = function (min, max, result) {
  1932. if (min === void 0) { min = 0; }
  1933. if (max === void 0) { max = 1; }
  1934. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1935. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1936. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1937. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  1938. return this;
  1939. };
  1940. /**
  1941. * Multipy an Color4 value by another and return a new Color4 object
  1942. * @param color defines the Color4 value to multiply by
  1943. * @returns a new Color4 object
  1944. */
  1945. Color4.prototype.multiply = function (color) {
  1946. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  1947. };
  1948. /**
  1949. * Multipy a Color4 value by another and push the result in a reference value
  1950. * @param color defines the Color4 value to multiply by
  1951. * @param result defines the Color4 to fill the result in
  1952. * @returns the result Color4
  1953. */
  1954. Color4.prototype.multiplyToRef = function (color, result) {
  1955. result.r = this.r * color.r;
  1956. result.g = this.g * color.g;
  1957. result.b = this.b * color.b;
  1958. result.a = this.a * color.a;
  1959. return result;
  1960. };
  1961. /**
  1962. * Creates a string with the Color4 current values
  1963. * @returns the string representation of the Color4 object
  1964. */
  1965. Color4.prototype.toString = function () {
  1966. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  1967. };
  1968. /**
  1969. * Returns the string "Color4"
  1970. * @returns "Color4"
  1971. */
  1972. Color4.prototype.getClassName = function () {
  1973. return "Color4";
  1974. };
  1975. /**
  1976. * Compute the Color4 hash code
  1977. * @returns an unique number that can be used to hash Color4 objects
  1978. */
  1979. Color4.prototype.getHashCode = function () {
  1980. var hash = this.r || 0;
  1981. hash = (hash * 397) ^ (this.g || 0);
  1982. hash = (hash * 397) ^ (this.b || 0);
  1983. hash = (hash * 397) ^ (this.a || 0);
  1984. return hash;
  1985. };
  1986. /**
  1987. * Creates a new Color4 copied from the current one
  1988. * @returns a new Color4 object
  1989. */
  1990. Color4.prototype.clone = function () {
  1991. return new Color4(this.r, this.g, this.b, this.a);
  1992. };
  1993. /**
  1994. * Copies the given Color4 values into the current one
  1995. * @param source defines the source Color4 object
  1996. * @returns the current updated Color4 object
  1997. */
  1998. Color4.prototype.copyFrom = function (source) {
  1999. this.r = source.r;
  2000. this.g = source.g;
  2001. this.b = source.b;
  2002. this.a = source.a;
  2003. return this;
  2004. };
  2005. /**
  2006. * Copies the given float values into the current one
  2007. * @param r defines the red component to read from
  2008. * @param g defines the green component to read from
  2009. * @param b defines the blue component to read from
  2010. * @param a defines the alpha component to read from
  2011. * @returns the current updated Color4 object
  2012. */
  2013. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2014. this.r = r;
  2015. this.g = g;
  2016. this.b = b;
  2017. this.a = a;
  2018. return this;
  2019. };
  2020. /**
  2021. * Copies the given float values into the current one
  2022. * @param r defines the red component to read from
  2023. * @param g defines the green component to read from
  2024. * @param b defines the blue component to read from
  2025. * @param a defines the alpha component to read from
  2026. * @returns the current updated Color4 object
  2027. */
  2028. Color4.prototype.set = function (r, g, b, a) {
  2029. return this.copyFromFloats(r, g, b, a);
  2030. };
  2031. /**
  2032. * Compute the Color4 hexadecimal code as a string
  2033. * @returns a string containing the hexadecimal representation of the Color4 object
  2034. */
  2035. Color4.prototype.toHexString = function () {
  2036. var intR = (this.r * 255) | 0;
  2037. var intG = (this.g * 255) | 0;
  2038. var intB = (this.b * 255) | 0;
  2039. var intA = (this.a * 255) | 0;
  2040. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2041. };
  2042. /**
  2043. * Computes a new Color4 converted from the current one to linear space
  2044. * @returns a new Color4 object
  2045. */
  2046. Color4.prototype.toLinearSpace = function () {
  2047. var convertedColor = new Color4();
  2048. this.toLinearSpaceToRef(convertedColor);
  2049. return convertedColor;
  2050. };
  2051. /**
  2052. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2053. * @param convertedColor defines the Color4 object where to store the linear space version
  2054. * @returns the unmodified Color4
  2055. */
  2056. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2057. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2058. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2059. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2060. convertedColor.a = this.a;
  2061. return this;
  2062. };
  2063. /**
  2064. * Computes a new Color4 converted from the current one to gamma space
  2065. * @returns a new Color4 object
  2066. */
  2067. Color4.prototype.toGammaSpace = function () {
  2068. var convertedColor = new Color4();
  2069. this.toGammaSpaceToRef(convertedColor);
  2070. return convertedColor;
  2071. };
  2072. /**
  2073. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2074. * @param convertedColor defines the Color4 object where to store the gamma space version
  2075. * @returns the unmodified Color4
  2076. */
  2077. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2078. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2079. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2080. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2081. convertedColor.a = this.a;
  2082. return this;
  2083. };
  2084. // Statics
  2085. /**
  2086. * Creates a new Color4 from the string containing valid hexadecimal values
  2087. * @param hex defines a string containing valid hexadecimal values
  2088. * @returns a new Color4 object
  2089. */
  2090. Color4.FromHexString = function (hex) {
  2091. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2092. return new Color4(0.0, 0.0, 0.0, 0.0);
  2093. }
  2094. var r = parseInt(hex.substring(1, 3), 16);
  2095. var g = parseInt(hex.substring(3, 5), 16);
  2096. var b = parseInt(hex.substring(5, 7), 16);
  2097. var a = parseInt(hex.substring(7, 9), 16);
  2098. return Color4.FromInts(r, g, b, a);
  2099. };
  2100. /**
  2101. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2102. * @param left defines the start value
  2103. * @param right defines the end value
  2104. * @param amount defines the gradient factor
  2105. * @returns a new Color4 object
  2106. */
  2107. Color4.Lerp = function (left, right, amount) {
  2108. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2109. Color4.LerpToRef(left, right, amount, result);
  2110. return result;
  2111. };
  2112. /**
  2113. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2114. * @param left defines the start value
  2115. * @param right defines the end value
  2116. * @param amount defines the gradient factor
  2117. * @param result defines the Color4 object where to store data
  2118. */
  2119. Color4.LerpToRef = function (left, right, amount, result) {
  2120. result.r = left.r + (right.r - left.r) * amount;
  2121. result.g = left.g + (right.g - left.g) * amount;
  2122. result.b = left.b + (right.b - left.b) * amount;
  2123. result.a = left.a + (right.a - left.a) * amount;
  2124. };
  2125. /**
  2126. * Creates a new Color4 from the starting index element of the given array
  2127. * @param array defines the source array to read from
  2128. * @param offset defines the offset in the source array
  2129. * @returns a new Color4 object
  2130. */
  2131. Color4.FromArray = function (array, offset) {
  2132. if (offset === void 0) { offset = 0; }
  2133. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2134. };
  2135. /**
  2136. * Creates a new Color3 from integer values (< 256)
  2137. * @param r defines the red component to read from (value between 0 and 255)
  2138. * @param g defines the green component to read from (value between 0 and 255)
  2139. * @param b defines the blue component to read from (value between 0 and 255)
  2140. * @param a defines the alpha component to read from (value between 0 and 255)
  2141. * @returns a new Color3 object
  2142. */
  2143. Color4.FromInts = function (r, g, b, a) {
  2144. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2145. };
  2146. /**
  2147. * Check the content of a given array and convert it to an array containing RGBA data
  2148. * If the original array was already containing count * 4 values then it is returned directly
  2149. * @param colors defines the array to check
  2150. * @param count defines the number of RGBA data to expect
  2151. * @returns an array containing count * 4 values (RGBA)
  2152. */
  2153. Color4.CheckColors4 = function (colors, count) {
  2154. // Check if color3 was used
  2155. if (colors.length === count * 3) {
  2156. var colors4 = [];
  2157. for (var index = 0; index < colors.length; index += 3) {
  2158. var newIndex = (index / 3) * 4;
  2159. colors4[newIndex] = colors[index];
  2160. colors4[newIndex + 1] = colors[index + 1];
  2161. colors4[newIndex + 2] = colors[index + 2];
  2162. colors4[newIndex + 3] = 1.0;
  2163. }
  2164. return colors4;
  2165. }
  2166. return colors;
  2167. };
  2168. return Color4;
  2169. }());
  2170. BABYLON.Color4 = Color4;
  2171. /**
  2172. * Class representing a vector containing 2 coordinates
  2173. */
  2174. var Vector2 = /** @class */ (function () {
  2175. /**
  2176. * Creates a new Vector2 from the given x and y coordinates
  2177. * @param x defines the first coordinate
  2178. * @param y defines the second coordinate
  2179. */
  2180. function Vector2(
  2181. /** defines the first coordinate */
  2182. x,
  2183. /** defines the second coordinate */
  2184. y) {
  2185. this.x = x;
  2186. this.y = y;
  2187. }
  2188. /**
  2189. * Gets a string with the Vector2 coordinates
  2190. * @returns a string with the Vector2 coordinates
  2191. */
  2192. Vector2.prototype.toString = function () {
  2193. return "{X: " + this.x + " Y:" + this.y + "}";
  2194. };
  2195. /**
  2196. * Gets class name
  2197. * @returns the string "Vector2"
  2198. */
  2199. Vector2.prototype.getClassName = function () {
  2200. return "Vector2";
  2201. };
  2202. /**
  2203. * Gets current vector hash code
  2204. * @returns the Vector2 hash code as a number
  2205. */
  2206. Vector2.prototype.getHashCode = function () {
  2207. var hash = this.x || 0;
  2208. hash = (hash * 397) ^ (this.y || 0);
  2209. return hash;
  2210. };
  2211. // Operators
  2212. /**
  2213. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2214. * @param array defines the source array
  2215. * @param index defines the offset in source array
  2216. * @returns the current Vector2
  2217. */
  2218. Vector2.prototype.toArray = function (array, index) {
  2219. if (index === void 0) { index = 0; }
  2220. array[index] = this.x;
  2221. array[index + 1] = this.y;
  2222. return this;
  2223. };
  2224. /**
  2225. * Copy the current vector to an array
  2226. * @returns a new array with 2 elements: the Vector2 coordinates.
  2227. */
  2228. Vector2.prototype.asArray = function () {
  2229. var result = new Array();
  2230. this.toArray(result, 0);
  2231. return result;
  2232. };
  2233. /**
  2234. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2235. * @param source defines the source Vector2
  2236. * @returns the current updated Vector2
  2237. */
  2238. Vector2.prototype.copyFrom = function (source) {
  2239. this.x = source.x;
  2240. this.y = source.y;
  2241. return this;
  2242. };
  2243. /**
  2244. * Sets the Vector2 coordinates with the given floats
  2245. * @param x defines the first coordinate
  2246. * @param y defines the second coordinate
  2247. * @returns the current updated Vector2
  2248. */
  2249. Vector2.prototype.copyFromFloats = function (x, y) {
  2250. this.x = x;
  2251. this.y = y;
  2252. return this;
  2253. };
  2254. /**
  2255. * Sets the Vector2 coordinates with the given floats
  2256. * @param x defines the first coordinate
  2257. * @param y defines the second coordinate
  2258. * @returns the current updated Vector2
  2259. */
  2260. Vector2.prototype.set = function (x, y) {
  2261. return this.copyFromFloats(x, y);
  2262. };
  2263. /**
  2264. * Add another vector with the current one
  2265. * @param otherVector defines the other vector
  2266. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2267. */
  2268. Vector2.prototype.add = function (otherVector) {
  2269. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2270. };
  2271. /**
  2272. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2273. * @param otherVector defines the other vector
  2274. * @param result defines the target vector
  2275. * @returns the unmodified current Vector2
  2276. */
  2277. Vector2.prototype.addToRef = function (otherVector, result) {
  2278. result.x = this.x + otherVector.x;
  2279. result.y = this.y + otherVector.y;
  2280. return this;
  2281. };
  2282. /**
  2283. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2284. * @param otherVector defines the other vector
  2285. * @returns the current updated Vector2
  2286. */
  2287. Vector2.prototype.addInPlace = function (otherVector) {
  2288. this.x += otherVector.x;
  2289. this.y += otherVector.y;
  2290. return this;
  2291. };
  2292. /**
  2293. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2294. * @param otherVector defines the other vector
  2295. * @returns a new Vector2
  2296. */
  2297. Vector2.prototype.addVector3 = function (otherVector) {
  2298. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2299. };
  2300. /**
  2301. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2302. * @param otherVector defines the other vector
  2303. * @returns a new Vector2
  2304. */
  2305. Vector2.prototype.subtract = function (otherVector) {
  2306. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2307. };
  2308. /**
  2309. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2310. * @param otherVector defines the other vector
  2311. * @param result defines the target vector
  2312. * @returns the unmodified current Vector2
  2313. */
  2314. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2315. result.x = this.x - otherVector.x;
  2316. result.y = this.y - otherVector.y;
  2317. return this;
  2318. };
  2319. /**
  2320. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2321. * @param otherVector defines the other vector
  2322. * @returns the current updated Vector2
  2323. */
  2324. Vector2.prototype.subtractInPlace = function (otherVector) {
  2325. this.x -= otherVector.x;
  2326. this.y -= otherVector.y;
  2327. return this;
  2328. };
  2329. /**
  2330. * Multiplies in place the current Vector2 coordinates by the given ones
  2331. * @param otherVector defines the other vector
  2332. * @returns the current updated Vector2
  2333. */
  2334. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2335. this.x *= otherVector.x;
  2336. this.y *= otherVector.y;
  2337. return this;
  2338. };
  2339. /**
  2340. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2341. * @param otherVector defines the other vector
  2342. * @returns a new Vector2
  2343. */
  2344. Vector2.prototype.multiply = function (otherVector) {
  2345. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2346. };
  2347. /**
  2348. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2349. * @param otherVector defines the other vector
  2350. * @param result defines the target vector
  2351. * @returns the unmodified current Vector2
  2352. */
  2353. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2354. result.x = this.x * otherVector.x;
  2355. result.y = this.y * otherVector.y;
  2356. return this;
  2357. };
  2358. /**
  2359. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2360. * @param x defines the first coordinate
  2361. * @param y defines the second coordinate
  2362. * @returns a new Vector2
  2363. */
  2364. Vector2.prototype.multiplyByFloats = function (x, y) {
  2365. return new Vector2(this.x * x, this.y * y);
  2366. };
  2367. /**
  2368. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2369. * @param otherVector defines the other vector
  2370. * @returns a new Vector2
  2371. */
  2372. Vector2.prototype.divide = function (otherVector) {
  2373. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2374. };
  2375. /**
  2376. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2377. * @param otherVector defines the other vector
  2378. * @param result defines the target vector
  2379. * @returns the unmodified current Vector2
  2380. */
  2381. Vector2.prototype.divideToRef = function (otherVector, result) {
  2382. result.x = this.x / otherVector.x;
  2383. result.y = this.y / otherVector.y;
  2384. return this;
  2385. };
  2386. /**
  2387. * Divides the current Vector3 coordinates by the given ones
  2388. * @param otherVector defines the other vector
  2389. * @returns the current updated Vector2
  2390. */
  2391. Vector2.prototype.divideInPlace = function (otherVector) {
  2392. return this.divideToRef(otherVector, this);
  2393. };
  2394. /**
  2395. * Gets a new Vector2 with current Vector2 negated coordinates
  2396. * @returns a new Vector2
  2397. */
  2398. Vector2.prototype.negate = function () {
  2399. return new Vector2(-this.x, -this.y);
  2400. };
  2401. /**
  2402. * Multiply the Vector2 coordinates by scale
  2403. * @param scale defines the scaling factor
  2404. * @returns the current updated Vector2
  2405. */
  2406. Vector2.prototype.scaleInPlace = function (scale) {
  2407. this.x *= scale;
  2408. this.y *= scale;
  2409. return this;
  2410. };
  2411. /**
  2412. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2413. * @param scale defines the scaling factor
  2414. * @returns a new Vector2
  2415. */
  2416. Vector2.prototype.scale = function (scale) {
  2417. var result = new Vector2(0, 0);
  2418. this.scaleToRef(scale, result);
  2419. return result;
  2420. };
  2421. /**
  2422. * Scale the current Vector2 values by a factor to a given Vector2
  2423. * @param scale defines the scale factor
  2424. * @param result defines the Vector2 object where to store the result
  2425. * @returns the unmodified current Vector2
  2426. */
  2427. Vector2.prototype.scaleToRef = function (scale, result) {
  2428. result.x = this.x * scale;
  2429. result.y = this.y * scale;
  2430. return this;
  2431. };
  2432. /**
  2433. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2434. * @param scale defines the scale factor
  2435. * @param result defines the Vector2 object where to store the result
  2436. * @returns the unmodified current Vector2
  2437. */
  2438. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2439. result.x += this.x * scale;
  2440. result.y += this.y * scale;
  2441. return this;
  2442. };
  2443. /**
  2444. * Gets a boolean if two vectors are equals
  2445. * @param otherVector defines the other vector
  2446. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2447. */
  2448. Vector2.prototype.equals = function (otherVector) {
  2449. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2450. };
  2451. /**
  2452. * Gets a boolean if two vectors are equals (using an epsilon value)
  2453. * @param otherVector defines the other vector
  2454. * @param epsilon defines the minimal distance to consider equality
  2455. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2456. */
  2457. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2458. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2459. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2460. };
  2461. // Properties
  2462. /**
  2463. * Gets the length of the vector
  2464. * @returns the vector length (float)
  2465. */
  2466. Vector2.prototype.length = function () {
  2467. return Math.sqrt(this.x * this.x + this.y * this.y);
  2468. };
  2469. /**
  2470. * Gets the vector squared length
  2471. * @returns the vector squared length (float)
  2472. */
  2473. Vector2.prototype.lengthSquared = function () {
  2474. return (this.x * this.x + this.y * this.y);
  2475. };
  2476. // Methods
  2477. /**
  2478. * Normalize the vector
  2479. * @returns the current updated Vector2
  2480. */
  2481. Vector2.prototype.normalize = function () {
  2482. var len = this.length();
  2483. if (len === 0)
  2484. return this;
  2485. var num = 1.0 / len;
  2486. this.x *= num;
  2487. this.y *= num;
  2488. return this;
  2489. };
  2490. /**
  2491. * Gets a new Vector2 copied from the Vector2
  2492. * @returns a new Vector2
  2493. */
  2494. Vector2.prototype.clone = function () {
  2495. return new Vector2(this.x, this.y);
  2496. };
  2497. // Statics
  2498. /**
  2499. * Gets a new Vector2(0, 0)
  2500. * @returns a new Vector2
  2501. */
  2502. Vector2.Zero = function () {
  2503. return new Vector2(0, 0);
  2504. };
  2505. /**
  2506. * Gets a new Vector2(1, 1)
  2507. * @returns a new Vector2
  2508. */
  2509. Vector2.One = function () {
  2510. return new Vector2(1, 1);
  2511. };
  2512. /**
  2513. * Gets a new Vector2 set from the given index element of the given array
  2514. * @param array defines the data source
  2515. * @param offset defines the offset in the data source
  2516. * @returns a new Vector2
  2517. */
  2518. Vector2.FromArray = function (array, offset) {
  2519. if (offset === void 0) { offset = 0; }
  2520. return new Vector2(array[offset], array[offset + 1]);
  2521. };
  2522. /**
  2523. * Sets "result" from the given index element of the given array
  2524. * @param array defines the data source
  2525. * @param offset defines the offset in the data source
  2526. * @param result defines the target vector
  2527. */
  2528. Vector2.FromArrayToRef = function (array, offset, result) {
  2529. result.x = array[offset];
  2530. result.y = array[offset + 1];
  2531. };
  2532. /**
  2533. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2534. * @param value1 defines 1st point of control
  2535. * @param value2 defines 2nd point of control
  2536. * @param value3 defines 3rd point of control
  2537. * @param value4 defines 4th point of control
  2538. * @param amount defines the interpolation factor
  2539. * @returns a new Vector2
  2540. */
  2541. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2542. var squared = amount * amount;
  2543. var cubed = amount * squared;
  2544. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2545. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2546. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2547. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2548. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2549. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2550. return new Vector2(x, y);
  2551. };
  2552. /**
  2553. * 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".
  2554. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2555. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2556. * @param value defines the value to clamp
  2557. * @param min defines the lower limit
  2558. * @param max defines the upper limit
  2559. * @returns a new Vector2
  2560. */
  2561. Vector2.Clamp = function (value, min, max) {
  2562. var x = value.x;
  2563. x = (x > max.x) ? max.x : x;
  2564. x = (x < min.x) ? min.x : x;
  2565. var y = value.y;
  2566. y = (y > max.y) ? max.y : y;
  2567. y = (y < min.y) ? min.y : y;
  2568. return new Vector2(x, y);
  2569. };
  2570. /**
  2571. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2572. * @param value1 defines the 1st control point
  2573. * @param tangent1 defines the outgoing tangent
  2574. * @param value2 defines the 2nd control point
  2575. * @param tangent2 defines the incoming tangent
  2576. * @param amount defines the interpolation factor
  2577. * @returns a new Vector2
  2578. */
  2579. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2580. var squared = amount * amount;
  2581. var cubed = amount * squared;
  2582. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2583. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2584. var part3 = (cubed - (2.0 * squared)) + amount;
  2585. var part4 = cubed - squared;
  2586. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2587. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2588. return new Vector2(x, y);
  2589. };
  2590. /**
  2591. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2592. * @param start defines the start vector
  2593. * @param end defines the end vector
  2594. * @param amount defines the interpolation factor
  2595. * @returns a new Vector2
  2596. */
  2597. Vector2.Lerp = function (start, end, amount) {
  2598. var x = start.x + ((end.x - start.x) * amount);
  2599. var y = start.y + ((end.y - start.y) * amount);
  2600. return new Vector2(x, y);
  2601. };
  2602. /**
  2603. * Gets the dot product of the vector "left" and the vector "right"
  2604. * @param left defines first vector
  2605. * @param right defines second vector
  2606. * @returns the dot product (float)
  2607. */
  2608. Vector2.Dot = function (left, right) {
  2609. return left.x * right.x + left.y * right.y;
  2610. };
  2611. /**
  2612. * Returns a new Vector2 equal to the normalized given vector
  2613. * @param vector defines the vector to normalize
  2614. * @returns a new Vector2
  2615. */
  2616. Vector2.Normalize = function (vector) {
  2617. var newVector = vector.clone();
  2618. newVector.normalize();
  2619. return newVector;
  2620. };
  2621. /**
  2622. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2623. * @param left defines 1st vector
  2624. * @param right defines 2nd vector
  2625. * @returns a new Vector2
  2626. */
  2627. Vector2.Minimize = function (left, right) {
  2628. var x = (left.x < right.x) ? left.x : right.x;
  2629. var y = (left.y < right.y) ? left.y : right.y;
  2630. return new Vector2(x, y);
  2631. };
  2632. /**
  2633. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2634. * @param left defines 1st vector
  2635. * @param right defines 2nd vector
  2636. * @returns a new Vector2
  2637. */
  2638. Vector2.Maximize = function (left, right) {
  2639. var x = (left.x > right.x) ? left.x : right.x;
  2640. var y = (left.y > right.y) ? left.y : right.y;
  2641. return new Vector2(x, y);
  2642. };
  2643. /**
  2644. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2645. * @param vector defines the vector to transform
  2646. * @param transformation defines the matrix to apply
  2647. * @returns a new Vector2
  2648. */
  2649. Vector2.Transform = function (vector, transformation) {
  2650. var r = Vector2.Zero();
  2651. Vector2.TransformToRef(vector, transformation, r);
  2652. return r;
  2653. };
  2654. /**
  2655. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2656. * @param vector defines the vector to transform
  2657. * @param transformation defines the matrix to apply
  2658. * @param result defines the target vector
  2659. */
  2660. Vector2.TransformToRef = function (vector, transformation, result) {
  2661. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2662. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2663. result.x = x;
  2664. result.y = y;
  2665. };
  2666. /**
  2667. * Determines if a given vector is included in a triangle
  2668. * @param p defines the vector to test
  2669. * @param p0 defines 1st triangle point
  2670. * @param p1 defines 2nd triangle point
  2671. * @param p2 defines 3rd triangle point
  2672. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2673. */
  2674. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2675. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2676. var sign = a < 0 ? -1 : 1;
  2677. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2678. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2679. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2680. };
  2681. /**
  2682. * Gets the distance between the vectors "value1" and "value2"
  2683. * @param value1 defines first vector
  2684. * @param value2 defines second vector
  2685. * @returns the distance between vectors
  2686. */
  2687. Vector2.Distance = function (value1, value2) {
  2688. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2689. };
  2690. /**
  2691. * Returns the squared distance between the vectors "value1" and "value2"
  2692. * @param value1 defines first vector
  2693. * @param value2 defines second vector
  2694. * @returns the squared distance between vectors
  2695. */
  2696. Vector2.DistanceSquared = function (value1, value2) {
  2697. var x = value1.x - value2.x;
  2698. var y = value1.y - value2.y;
  2699. return (x * x) + (y * y);
  2700. };
  2701. /**
  2702. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2703. * @param value1 defines first vector
  2704. * @param value2 defines second vector
  2705. * @returns a new Vector2
  2706. */
  2707. Vector2.Center = function (value1, value2) {
  2708. var center = value1.add(value2);
  2709. center.scaleInPlace(0.5);
  2710. return center;
  2711. };
  2712. /**
  2713. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2714. * @param p defines the middle point
  2715. * @param segA defines one point of the segment
  2716. * @param segB defines the other point of the segment
  2717. * @returns the shortest distance
  2718. */
  2719. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2720. var l2 = Vector2.DistanceSquared(segA, segB);
  2721. if (l2 === 0.0) {
  2722. return Vector2.Distance(p, segA);
  2723. }
  2724. var v = segB.subtract(segA);
  2725. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2726. var proj = segA.add(v.multiplyByFloats(t, t));
  2727. return Vector2.Distance(p, proj);
  2728. };
  2729. return Vector2;
  2730. }());
  2731. BABYLON.Vector2 = Vector2;
  2732. /**
  2733. * Classed used to store (x,y,z) vector representation
  2734. * A Vector3 is the main object used in 3D geometry
  2735. * It can represent etiher the coordinates of a point the space, either a direction
  2736. * Reminder: Babylon.js uses a left handed forward facing system
  2737. */
  2738. var Vector3 = /** @class */ (function () {
  2739. /**
  2740. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2741. * @param x defines the first coordinates (on X axis)
  2742. * @param y defines the second coordinates (on Y axis)
  2743. * @param z defines the third coordinates (on Z axis)
  2744. */
  2745. function Vector3(
  2746. /**
  2747. * Defines the first coordinates (on X axis)
  2748. */
  2749. x,
  2750. /**
  2751. * Defines the second coordinates (on Y axis)
  2752. */
  2753. y,
  2754. /**
  2755. * Defines the third coordinates (on Z axis)
  2756. */
  2757. z) {
  2758. this.x = x;
  2759. this.y = y;
  2760. this.z = z;
  2761. }
  2762. /**
  2763. * Creates a string representation of the Vector3
  2764. * @returns a string with the Vector3 coordinates.
  2765. */
  2766. Vector3.prototype.toString = function () {
  2767. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2768. };
  2769. /**
  2770. * Gets the class name
  2771. * @returns the string "Vector3"
  2772. */
  2773. Vector3.prototype.getClassName = function () {
  2774. return "Vector3";
  2775. };
  2776. /**
  2777. * Creates the Vector3 hash code
  2778. * @returns a number which tends to be unique between Vector3 instances
  2779. */
  2780. Vector3.prototype.getHashCode = function () {
  2781. var hash = this.x || 0;
  2782. hash = (hash * 397) ^ (this.y || 0);
  2783. hash = (hash * 397) ^ (this.z || 0);
  2784. return hash;
  2785. };
  2786. // Operators
  2787. /**
  2788. * Creates an array containing three elements : the coordinates of the Vector3
  2789. * @returns a new array of numbers
  2790. */
  2791. Vector3.prototype.asArray = function () {
  2792. var result = [];
  2793. this.toArray(result, 0);
  2794. return result;
  2795. };
  2796. /**
  2797. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2798. * @param array defines the destination array
  2799. * @param index defines the offset in the destination array
  2800. * @returns the current Vector3
  2801. */
  2802. Vector3.prototype.toArray = function (array, index) {
  2803. if (index === void 0) { index = 0; }
  2804. array[index] = this.x;
  2805. array[index + 1] = this.y;
  2806. array[index + 2] = this.z;
  2807. return this;
  2808. };
  2809. /**
  2810. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2811. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2812. */
  2813. Vector3.prototype.toQuaternion = function () {
  2814. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2815. };
  2816. /**
  2817. * Adds the given vector to the current Vector3
  2818. * @param otherVector defines the second operand
  2819. * @returns the current updated Vector3
  2820. */
  2821. Vector3.prototype.addInPlace = function (otherVector) {
  2822. this.x += otherVector.x;
  2823. this.y += otherVector.y;
  2824. this.z += otherVector.z;
  2825. return this;
  2826. };
  2827. /**
  2828. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2829. * @param otherVector defines the second operand
  2830. * @returns the resulting Vector3
  2831. */
  2832. Vector3.prototype.add = function (otherVector) {
  2833. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2834. };
  2835. /**
  2836. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2837. * @param otherVector defines the second operand
  2838. * @param result defines the Vector3 object where to store the result
  2839. * @returns the current Vector3
  2840. */
  2841. Vector3.prototype.addToRef = function (otherVector, result) {
  2842. result.x = this.x + otherVector.x;
  2843. result.y = this.y + otherVector.y;
  2844. result.z = this.z + otherVector.z;
  2845. return this;
  2846. };
  2847. /**
  2848. * Subtract the given vector from the current Vector3
  2849. * @param otherVector defines the second operand
  2850. * @returns the current updated Vector3
  2851. */
  2852. Vector3.prototype.subtractInPlace = function (otherVector) {
  2853. this.x -= otherVector.x;
  2854. this.y -= otherVector.y;
  2855. this.z -= otherVector.z;
  2856. return this;
  2857. };
  2858. /**
  2859. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2860. * @param otherVector defines the second operand
  2861. * @returns the resulting Vector3
  2862. */
  2863. Vector3.prototype.subtract = function (otherVector) {
  2864. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2865. };
  2866. /**
  2867. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2868. * @param otherVector defines the second operand
  2869. * @param result defines the Vector3 object where to store the result
  2870. * @returns the current Vector3
  2871. */
  2872. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2873. result.x = this.x - otherVector.x;
  2874. result.y = this.y - otherVector.y;
  2875. result.z = this.z - otherVector.z;
  2876. return this;
  2877. };
  2878. /**
  2879. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2880. * @param x defines the x coordinate of the operand
  2881. * @param y defines the y coordinate of the operand
  2882. * @param z defines the z coordinate of the operand
  2883. * @returns the resulting Vector3
  2884. */
  2885. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  2886. return new Vector3(this.x - x, this.y - y, this.z - z);
  2887. };
  2888. /**
  2889. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  2890. * @param x defines the x coordinate of the operand
  2891. * @param y defines the y coordinate of the operand
  2892. * @param z defines the z coordinate of the operand
  2893. * @param result defines the Vector3 object where to store the result
  2894. * @returns the current Vector3
  2895. */
  2896. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  2897. result.x = this.x - x;
  2898. result.y = this.y - y;
  2899. result.z = this.z - z;
  2900. return this;
  2901. };
  2902. /**
  2903. * Gets a new Vector3 set with the current Vector3 negated coordinates
  2904. * @returns a new Vector3
  2905. */
  2906. Vector3.prototype.negate = function () {
  2907. return new Vector3(-this.x, -this.y, -this.z);
  2908. };
  2909. /**
  2910. * Multiplies the Vector3 coordinates by the float "scale"
  2911. * @param scale defines the multiplier factor
  2912. * @returns the current updated Vector3
  2913. */
  2914. Vector3.prototype.scaleInPlace = function (scale) {
  2915. this.x *= scale;
  2916. this.y *= scale;
  2917. this.z *= scale;
  2918. return this;
  2919. };
  2920. /**
  2921. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  2922. * @param scale defines the multiplier factor
  2923. * @returns a new Vector3
  2924. */
  2925. Vector3.prototype.scale = function (scale) {
  2926. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  2927. };
  2928. /**
  2929. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  2930. * @param scale defines the multiplier factor
  2931. * @param result defines the Vector3 object where to store the result
  2932. * @returns the current Vector3
  2933. */
  2934. Vector3.prototype.scaleToRef = function (scale, result) {
  2935. result.x = this.x * scale;
  2936. result.y = this.y * scale;
  2937. result.z = this.z * scale;
  2938. return this;
  2939. };
  2940. /**
  2941. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  2942. * @param scale defines the scale factor
  2943. * @param result defines the Vector3 object where to store the result
  2944. * @returns the unmodified current Vector3
  2945. */
  2946. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  2947. result.x += this.x * scale;
  2948. result.y += this.y * scale;
  2949. result.z += this.z * scale;
  2950. return this;
  2951. };
  2952. /**
  2953. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  2954. * @param otherVector defines the second operand
  2955. * @returns true if both vectors are equals
  2956. */
  2957. Vector3.prototype.equals = function (otherVector) {
  2958. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  2959. };
  2960. /**
  2961. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  2962. * @param otherVector defines the second operand
  2963. * @param epsilon defines the minimal distance to define values as equals
  2964. * @returns true if both vectors are distant less than epsilon
  2965. */
  2966. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2967. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2968. 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);
  2969. };
  2970. /**
  2971. * Returns true if the current Vector3 coordinates equals the given floats
  2972. * @param x defines the x coordinate of the operand
  2973. * @param y defines the y coordinate of the operand
  2974. * @param z defines the z coordinate of the operand
  2975. * @returns true if both vectors are equals
  2976. */
  2977. Vector3.prototype.equalsToFloats = function (x, y, z) {
  2978. return this.x === x && this.y === y && this.z === z;
  2979. };
  2980. /**
  2981. * Multiplies the current Vector3 coordinates by the given ones
  2982. * @param otherVector defines the second operand
  2983. * @returns the current updated Vector3
  2984. */
  2985. Vector3.prototype.multiplyInPlace = function (otherVector) {
  2986. this.x *= otherVector.x;
  2987. this.y *= otherVector.y;
  2988. this.z *= otherVector.z;
  2989. return this;
  2990. };
  2991. /**
  2992. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  2993. * @param otherVector defines the second operand
  2994. * @returns the new Vector3
  2995. */
  2996. Vector3.prototype.multiply = function (otherVector) {
  2997. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  2998. };
  2999. /**
  3000. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3001. * @param otherVector defines the second operand
  3002. * @param result defines the Vector3 object where to store the result
  3003. * @returns the current Vector3
  3004. */
  3005. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3006. result.x = this.x * otherVector.x;
  3007. result.y = this.y * otherVector.y;
  3008. result.z = this.z * otherVector.z;
  3009. return this;
  3010. };
  3011. /**
  3012. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3013. * @param x defines the x coordinate of the operand
  3014. * @param y defines the y coordinate of the operand
  3015. * @param z defines the z coordinate of the operand
  3016. * @returns the new Vector3
  3017. */
  3018. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3019. return new Vector3(this.x * x, this.y * y, this.z * z);
  3020. };
  3021. /**
  3022. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3023. * @param otherVector defines the second operand
  3024. * @returns the new Vector3
  3025. */
  3026. Vector3.prototype.divide = function (otherVector) {
  3027. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3028. };
  3029. /**
  3030. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3031. * @param otherVector defines the second operand
  3032. * @param result defines the Vector3 object where to store the result
  3033. * @returns the current Vector3
  3034. */
  3035. Vector3.prototype.divideToRef = function (otherVector, result) {
  3036. result.x = this.x / otherVector.x;
  3037. result.y = this.y / otherVector.y;
  3038. result.z = this.z / otherVector.z;
  3039. return this;
  3040. };
  3041. /**
  3042. * Divides the current Vector3 coordinates by the given ones.
  3043. * @param otherVector defines the second operand
  3044. * @returns the current updated Vector3
  3045. */
  3046. Vector3.prototype.divideInPlace = function (otherVector) {
  3047. return this.divideToRef(otherVector, this);
  3048. };
  3049. /**
  3050. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3051. * @param other defines the second operand
  3052. * @returns the current updated Vector3
  3053. */
  3054. Vector3.prototype.minimizeInPlace = function (other) {
  3055. if (other.x < this.x)
  3056. this.x = other.x;
  3057. if (other.y < this.y)
  3058. this.y = other.y;
  3059. if (other.z < this.z)
  3060. this.z = other.z;
  3061. return this;
  3062. };
  3063. /**
  3064. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3065. * @param other defines the second operand
  3066. * @returns the current updated Vector3
  3067. */
  3068. Vector3.prototype.maximizeInPlace = function (other) {
  3069. if (other.x > this.x)
  3070. this.x = other.x;
  3071. if (other.y > this.y)
  3072. this.y = other.y;
  3073. if (other.z > this.z)
  3074. this.z = other.z;
  3075. return this;
  3076. };
  3077. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3078. /**
  3079. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3080. */
  3081. get: function () {
  3082. var absX = Math.abs(this.x);
  3083. var absY = Math.abs(this.y);
  3084. if (absX !== absY) {
  3085. return true;
  3086. }
  3087. var absZ = Math.abs(this.z);
  3088. if (absX !== absZ) {
  3089. return true;
  3090. }
  3091. if (absY !== absZ) {
  3092. return true;
  3093. }
  3094. return false;
  3095. },
  3096. enumerable: true,
  3097. configurable: true
  3098. });
  3099. // Properties
  3100. /**
  3101. * Gets the length of the Vector3
  3102. * @returns the length of the Vecto3
  3103. */
  3104. Vector3.prototype.length = function () {
  3105. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3106. };
  3107. /**
  3108. * Gets the squared length of the Vector3
  3109. * @returns squared length of the Vector3
  3110. */
  3111. Vector3.prototype.lengthSquared = function () {
  3112. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3113. };
  3114. /**
  3115. * Normalize the current Vector3.
  3116. * Please note that this is an in place operation.
  3117. * @returns the current updated Vector3
  3118. */
  3119. Vector3.prototype.normalize = function () {
  3120. var len = this.length();
  3121. if (len === 0 || len === 1.0)
  3122. return this;
  3123. var num = 1.0 / len;
  3124. this.x *= num;
  3125. this.y *= num;
  3126. this.z *= num;
  3127. return this;
  3128. };
  3129. /**
  3130. * Normalize the current Vector3 to a new vector
  3131. * @returns the new Vector3
  3132. */
  3133. Vector3.prototype.normalizeToNew = function () {
  3134. var normalized = new Vector3(0, 0, 0);
  3135. this.normalizeToRef(normalized);
  3136. return normalized;
  3137. };
  3138. /**
  3139. * Normalize the current Vector3 to the reference
  3140. * @param reference define the Vector3 to update
  3141. * @returns the updated Vector3
  3142. */
  3143. Vector3.prototype.normalizeToRef = function (reference) {
  3144. var len = this.length();
  3145. if (len === 0 || len === 1.0) {
  3146. reference.set(this.x, this.y, this.z);
  3147. return reference;
  3148. }
  3149. var scale = 1.0 / len;
  3150. this.scaleToRef(scale, reference);
  3151. return reference;
  3152. };
  3153. /**
  3154. * Creates a new Vector3 copied from the current Vector3
  3155. * @returns the new Vector3
  3156. */
  3157. Vector3.prototype.clone = function () {
  3158. return new Vector3(this.x, this.y, this.z);
  3159. };
  3160. /**
  3161. * Copies the given vector coordinates to the current Vector3 ones
  3162. * @param source defines the source Vector3
  3163. * @returns the current updated Vector3
  3164. */
  3165. Vector3.prototype.copyFrom = function (source) {
  3166. this.x = source.x;
  3167. this.y = source.y;
  3168. this.z = source.z;
  3169. return this;
  3170. };
  3171. /**
  3172. * Copies the given floats to the current Vector3 coordinates
  3173. * @param x defines the x coordinate of the operand
  3174. * @param y defines the y coordinate of the operand
  3175. * @param z defines the z coordinate of the operand
  3176. * @returns the current updated Vector3
  3177. */
  3178. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3179. this.x = x;
  3180. this.y = y;
  3181. this.z = z;
  3182. return this;
  3183. };
  3184. /**
  3185. * Copies the given floats to the current Vector3 coordinates
  3186. * @param x defines the x coordinate of the operand
  3187. * @param y defines the y coordinate of the operand
  3188. * @param z defines the z coordinate of the operand
  3189. * @returns the current updated Vector3
  3190. */
  3191. Vector3.prototype.set = function (x, y, z) {
  3192. return this.copyFromFloats(x, y, z);
  3193. };
  3194. // Statics
  3195. /**
  3196. * Get the clip factor between two vectors
  3197. * @param vector0 defines the first operand
  3198. * @param vector1 defines the second operand
  3199. * @param axis defines the axis to use
  3200. * @param size defines the size along the axis
  3201. * @returns the clip factor
  3202. */
  3203. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3204. var d0 = Vector3.Dot(vector0, axis) - size;
  3205. var d1 = Vector3.Dot(vector1, axis) - size;
  3206. var s = d0 / (d0 - d1);
  3207. return s;
  3208. };
  3209. /**
  3210. * Get angle between two vectors
  3211. * @param vector0 angle between vector0 and vector1
  3212. * @param vector1 angle between vector0 and vector1
  3213. * @param normal direction of the normal
  3214. * @return the angle between vector0 and vector1
  3215. */
  3216. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3217. var v0 = vector0.clone().normalize();
  3218. var v1 = vector1.clone().normalize();
  3219. var dot = Vector3.Dot(v0, v1);
  3220. var n = Vector3.Cross(v0, v1);
  3221. if (Vector3.Dot(n, normal) > 0) {
  3222. return Math.acos(dot);
  3223. }
  3224. return -Math.acos(dot);
  3225. };
  3226. /**
  3227. * Returns a new Vector3 set from the index "offset" of the given array
  3228. * @param array defines the source array
  3229. * @param offset defines the offset in the source array
  3230. * @returns the new Vector3
  3231. */
  3232. Vector3.FromArray = function (array, offset) {
  3233. if (!offset) {
  3234. offset = 0;
  3235. }
  3236. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3237. };
  3238. /**
  3239. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3240. * This function is deprecated. Use FromArray instead
  3241. * @param array defines the source array
  3242. * @param offset defines the offset in the source array
  3243. * @returns the new Vector3
  3244. */
  3245. Vector3.FromFloatArray = function (array, offset) {
  3246. return Vector3.FromArray(array, offset);
  3247. };
  3248. /**
  3249. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3250. * @param array defines the source array
  3251. * @param offset defines the offset in the source array
  3252. * @param result defines the Vector3 where to store the result
  3253. */
  3254. Vector3.FromArrayToRef = function (array, offset, result) {
  3255. result.x = array[offset];
  3256. result.y = array[offset + 1];
  3257. result.z = array[offset + 2];
  3258. };
  3259. /**
  3260. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3261. * This function is deprecated. Use FromArrayToRef instead.
  3262. * @param array defines the source array
  3263. * @param offset defines the offset in the source array
  3264. * @param result defines the Vector3 where to store the result
  3265. */
  3266. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3267. return Vector3.FromArrayToRef(array, offset, result);
  3268. };
  3269. /**
  3270. * Sets the given vector "result" with the given floats.
  3271. * @param x defines the x coordinate of the source
  3272. * @param y defines the y coordinate of the source
  3273. * @param z defines the z coordinate of the source
  3274. * @param result defines the Vector3 where to store the result
  3275. */
  3276. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3277. result.x = x;
  3278. result.y = y;
  3279. result.z = z;
  3280. };
  3281. /**
  3282. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3283. * @returns a new empty Vector3
  3284. */
  3285. Vector3.Zero = function () {
  3286. return new Vector3(0.0, 0.0, 0.0);
  3287. };
  3288. /**
  3289. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3290. * @returns a new unit Vector3
  3291. */
  3292. Vector3.One = function () {
  3293. return new Vector3(1.0, 1.0, 1.0);
  3294. };
  3295. /**
  3296. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3297. * @returns a new up Vector3
  3298. */
  3299. Vector3.Up = function () {
  3300. return new Vector3(0.0, 1.0, 0.0);
  3301. };
  3302. /**
  3303. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3304. * @returns a new forward Vector3
  3305. */
  3306. Vector3.Forward = function () {
  3307. return new Vector3(0.0, 0.0, 1.0);
  3308. };
  3309. /**
  3310. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3311. * @returns a new right Vector3
  3312. */
  3313. Vector3.Right = function () {
  3314. return new Vector3(1.0, 0.0, 0.0);
  3315. };
  3316. /**
  3317. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3318. * @returns a new left Vector3
  3319. */
  3320. Vector3.Left = function () {
  3321. return new Vector3(-1.0, 0.0, 0.0);
  3322. };
  3323. /**
  3324. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3325. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3326. * @param vector defines the Vector3 to transform
  3327. * @param transformation defines the transformation matrix
  3328. * @returns the transformed Vector3
  3329. */
  3330. Vector3.TransformCoordinates = function (vector, transformation) {
  3331. var result = Vector3.Zero();
  3332. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3333. return result;
  3334. };
  3335. /**
  3336. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3337. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3338. * @param vector defines the Vector3 to transform
  3339. * @param transformation defines the transformation matrix
  3340. * @param result defines the Vector3 where to store the result
  3341. */
  3342. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3343. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3344. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3345. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3346. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3347. result.x = x / w;
  3348. result.y = y / w;
  3349. result.z = z / w;
  3350. };
  3351. /**
  3352. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3353. * This method computes tranformed coordinates only, not transformed direction vectors
  3354. * @param x define the x coordinate of the source vector
  3355. * @param y define the y coordinate of the source vector
  3356. * @param z define the z coordinate of the source vector
  3357. * @param transformation defines the transformation matrix
  3358. * @param result defines the Vector3 where to store the result
  3359. */
  3360. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3361. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3362. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3363. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3364. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3365. result.x = rx / rw;
  3366. result.y = ry / rw;
  3367. result.z = rz / rw;
  3368. };
  3369. /**
  3370. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3371. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3372. * @param vector defines the Vector3 to transform
  3373. * @param transformation defines the transformation matrix
  3374. * @returns the new Vector3
  3375. */
  3376. Vector3.TransformNormal = function (vector, transformation) {
  3377. var result = Vector3.Zero();
  3378. Vector3.TransformNormalToRef(vector, transformation, result);
  3379. return result;
  3380. };
  3381. /**
  3382. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3383. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3384. * @param vector defines the Vector3 to transform
  3385. * @param transformation defines the transformation matrix
  3386. * @param result defines the Vector3 where to store the result
  3387. */
  3388. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3389. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3390. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3391. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3392. result.x = x;
  3393. result.y = y;
  3394. result.z = z;
  3395. };
  3396. /**
  3397. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3398. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3399. * @param x define the x coordinate of the source vector
  3400. * @param y define the y coordinate of the source vector
  3401. * @param z define the z coordinate of the source vector
  3402. * @param transformation defines the transformation matrix
  3403. * @param result defines the Vector3 where to store the result
  3404. */
  3405. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3406. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3407. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3408. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3409. };
  3410. /**
  3411. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3412. * @param value1 defines the first control point
  3413. * @param value2 defines the second control point
  3414. * @param value3 defines the third control point
  3415. * @param value4 defines the fourth control point
  3416. * @param amount defines the amount on the spline to use
  3417. * @returns the new Vector3
  3418. */
  3419. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3420. var squared = amount * amount;
  3421. var cubed = amount * squared;
  3422. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3423. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3424. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3425. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3426. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3427. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3428. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3429. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3430. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3431. return new Vector3(x, y, z);
  3432. };
  3433. /**
  3434. * 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"
  3435. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3436. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3437. * @param value defines the current value
  3438. * @param min defines the lower range value
  3439. * @param max defines the upper range value
  3440. * @returns the new Vector3
  3441. */
  3442. Vector3.Clamp = function (value, min, max) {
  3443. var x = value.x;
  3444. x = (x > max.x) ? max.x : x;
  3445. x = (x < min.x) ? min.x : x;
  3446. var y = value.y;
  3447. y = (y > max.y) ? max.y : y;
  3448. y = (y < min.y) ? min.y : y;
  3449. var z = value.z;
  3450. z = (z > max.z) ? max.z : z;
  3451. z = (z < min.z) ? min.z : z;
  3452. return new Vector3(x, y, z);
  3453. };
  3454. /**
  3455. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3456. * @param value1 defines the first control point
  3457. * @param tangent1 defines the first tangent vector
  3458. * @param value2 defines the second control point
  3459. * @param tangent2 defines the second tangent vector
  3460. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3461. * @returns the new Vector3
  3462. */
  3463. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3464. var squared = amount * amount;
  3465. var cubed = amount * squared;
  3466. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3467. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3468. var part3 = (cubed - (2.0 * squared)) + amount;
  3469. var part4 = cubed - squared;
  3470. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3471. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3472. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3473. return new Vector3(x, y, z);
  3474. };
  3475. /**
  3476. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3477. * @param start defines the start value
  3478. * @param end defines the end value
  3479. * @param amount max defines amount between both (between 0 and 1)
  3480. * @returns the new Vector3
  3481. */
  3482. Vector3.Lerp = function (start, end, amount) {
  3483. var result = new Vector3(0, 0, 0);
  3484. Vector3.LerpToRef(start, end, amount, result);
  3485. return result;
  3486. };
  3487. /**
  3488. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3489. * @param start defines the start value
  3490. * @param end defines the end value
  3491. * @param amount max defines amount between both (between 0 and 1)
  3492. * @param result defines the Vector3 where to store the result
  3493. */
  3494. Vector3.LerpToRef = function (start, end, amount, result) {
  3495. result.x = start.x + ((end.x - start.x) * amount);
  3496. result.y = start.y + ((end.y - start.y) * amount);
  3497. result.z = start.z + ((end.z - start.z) * amount);
  3498. };
  3499. /**
  3500. * Returns the dot product (float) between the vectors "left" and "right"
  3501. * @param left defines the left operand
  3502. * @param right defines the right operand
  3503. * @returns the dot product
  3504. */
  3505. Vector3.Dot = function (left, right) {
  3506. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3507. };
  3508. /**
  3509. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3510. * The cross product is then orthogonal to both "left" and "right"
  3511. * @param left defines the left operand
  3512. * @param right defines the right operand
  3513. * @returns the cross product
  3514. */
  3515. Vector3.Cross = function (left, right) {
  3516. var result = Vector3.Zero();
  3517. Vector3.CrossToRef(left, right, result);
  3518. return result;
  3519. };
  3520. /**
  3521. * Sets the given vector "result" with the cross product of "left" and "right"
  3522. * The cross product is then orthogonal to both "left" and "right"
  3523. * @param left defines the left operand
  3524. * @param right defines the right operand
  3525. * @param result defines the Vector3 where to store the result
  3526. */
  3527. Vector3.CrossToRef = function (left, right, result) {
  3528. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3529. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3530. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3531. result.copyFrom(MathTmp.Vector3[0]);
  3532. };
  3533. /**
  3534. * Returns a new Vector3 as the normalization of the given vector
  3535. * @param vector defines the Vector3 to normalize
  3536. * @returns the new Vector3
  3537. */
  3538. Vector3.Normalize = function (vector) {
  3539. var result = Vector3.Zero();
  3540. Vector3.NormalizeToRef(vector, result);
  3541. return result;
  3542. };
  3543. /**
  3544. * Sets the given vector "result" with the normalization of the given first vector
  3545. * @param vector defines the Vector3 to normalize
  3546. * @param result defines the Vector3 where to store the result
  3547. */
  3548. Vector3.NormalizeToRef = function (vector, result) {
  3549. result.copyFrom(vector);
  3550. result.normalize();
  3551. };
  3552. /**
  3553. * Project a Vector3 onto screen space
  3554. * @param vector defines the Vector3 to project
  3555. * @param world defines the world matrix to use
  3556. * @param transform defines the transform (view x projection) matrix to use
  3557. * @param viewport defines the screen viewport to use
  3558. * @returns the new Vector3
  3559. */
  3560. Vector3.Project = function (vector, world, transform, viewport) {
  3561. var cw = viewport.width;
  3562. var ch = viewport.height;
  3563. var cx = viewport.x;
  3564. var cy = viewport.y;
  3565. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3566. 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);
  3567. var matrix = MathTmp.Matrix[0];
  3568. world.multiplyToRef(transform, matrix);
  3569. matrix.multiplyToRef(viewportMatrix, matrix);
  3570. return Vector3.TransformCoordinates(vector, matrix);
  3571. };
  3572. /**
  3573. * Unproject from screen space to object space
  3574. * @param source defines the screen space Vector3 to use
  3575. * @param viewportWidth defines the current width of the viewport
  3576. * @param viewportHeight defines the current height of the viewport
  3577. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3578. * @param transform defines the transform (view x projection) matrix to use
  3579. * @returns the new Vector3
  3580. */
  3581. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3582. var matrix = MathTmp.Matrix[0];
  3583. world.multiplyToRef(transform, matrix);
  3584. matrix.invert();
  3585. source.x = source.x / viewportWidth * 2 - 1;
  3586. source.y = -(source.y / viewportHeight * 2 - 1);
  3587. var vector = Vector3.TransformCoordinates(source, matrix);
  3588. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3589. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3590. vector = vector.scale(1.0 / num);
  3591. }
  3592. return vector;
  3593. };
  3594. /**
  3595. * Unproject from screen space to object space
  3596. * @param source defines the screen space Vector3 to use
  3597. * @param viewportWidth defines the current width of the viewport
  3598. * @param viewportHeight defines the current height of the viewport
  3599. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3600. * @param view defines the view matrix to use
  3601. * @param projection defines the projection matrix to use
  3602. * @returns the new Vector3
  3603. */
  3604. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3605. var result = Vector3.Zero();
  3606. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3607. return result;
  3608. };
  3609. /**
  3610. * Unproject from screen space to object space
  3611. * @param source defines the screen space Vector3 to use
  3612. * @param viewportWidth defines the current width of the viewport
  3613. * @param viewportHeight defines the current height of the viewport
  3614. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3615. * @param view defines the view matrix to use
  3616. * @param projection defines the projection matrix to use
  3617. * @param result defines the Vector3 where to store the result
  3618. */
  3619. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3620. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3621. };
  3622. /**
  3623. * Unproject from screen space to object space
  3624. * @param sourceX defines the screen space x coordinate to use
  3625. * @param sourceY defines the screen space y coordinate to use
  3626. * @param sourceZ defines the screen space z coordinate to use
  3627. * @param viewportWidth defines the current width of the viewport
  3628. * @param viewportHeight defines the current height of the viewport
  3629. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3630. * @param view defines the view matrix to use
  3631. * @param projection defines the projection matrix to use
  3632. * @param result defines the Vector3 where to store the result
  3633. */
  3634. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3635. var matrix = MathTmp.Matrix[0];
  3636. world.multiplyToRef(view, matrix);
  3637. matrix.multiplyToRef(projection, matrix);
  3638. matrix.invert();
  3639. var screenSource = MathTmp.Vector3[0];
  3640. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3641. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3642. screenSource.z = 2 * sourceZ - 1.0;
  3643. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3644. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3645. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3646. result.scaleInPlace(1.0 / num);
  3647. }
  3648. };
  3649. /**
  3650. * Gets the minimal coordinate values between two Vector3
  3651. * @param left defines the first operand
  3652. * @param right defines the second operand
  3653. * @returns the new Vector3
  3654. */
  3655. Vector3.Minimize = function (left, right) {
  3656. var min = left.clone();
  3657. min.minimizeInPlace(right);
  3658. return min;
  3659. };
  3660. /**
  3661. * Gets the maximal 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.Maximize = function (left, right) {
  3667. var max = left.clone();
  3668. max.maximizeInPlace(right);
  3669. return max;
  3670. };
  3671. /**
  3672. * Returns the distance between the vectors "value1" and "value2"
  3673. * @param value1 defines the first operand
  3674. * @param value2 defines the second operand
  3675. * @returns the distance
  3676. */
  3677. Vector3.Distance = function (value1, value2) {
  3678. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3679. };
  3680. /**
  3681. * Returns the squared distance between the vectors "value1" and "value2"
  3682. * @param value1 defines the first operand
  3683. * @param value2 defines the second operand
  3684. * @returns the squared distance
  3685. */
  3686. Vector3.DistanceSquared = function (value1, value2) {
  3687. var x = value1.x - value2.x;
  3688. var y = value1.y - value2.y;
  3689. var z = value1.z - value2.z;
  3690. return (x * x) + (y * y) + (z * z);
  3691. };
  3692. /**
  3693. * Returns a new Vector3 located at the center between "value1" and "value2"
  3694. * @param value1 defines the first operand
  3695. * @param value2 defines the second operand
  3696. * @returns the new Vector3
  3697. */
  3698. Vector3.Center = function (value1, value2) {
  3699. var center = value1.add(value2);
  3700. center.scaleInPlace(0.5);
  3701. return center;
  3702. };
  3703. /**
  3704. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3705. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3706. * to something in order to rotate it from its local system to the given target system
  3707. * Note: axis1, axis2 and axis3 are normalized during this operation
  3708. * @param axis1 defines the first axis
  3709. * @param axis2 defines the second axis
  3710. * @param axis3 defines the third axis
  3711. * @returns a new Vector3
  3712. */
  3713. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3714. var rotation = Vector3.Zero();
  3715. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3716. return rotation;
  3717. };
  3718. /**
  3719. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3720. * @param axis1 defines the first axis
  3721. * @param axis2 defines the second axis
  3722. * @param axis3 defines the third axis
  3723. * @param ref defines the Vector3 where to store the result
  3724. */
  3725. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3726. var quat = MathTmp.Quaternion[0];
  3727. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3728. quat.toEulerAnglesToRef(ref);
  3729. };
  3730. return Vector3;
  3731. }());
  3732. BABYLON.Vector3 = Vector3;
  3733. //Vector4 class created for EulerAngle class conversion to Quaternion
  3734. var Vector4 = /** @class */ (function () {
  3735. /**
  3736. * Creates a Vector4 object from the given floats.
  3737. */
  3738. function Vector4(x, y, z, w) {
  3739. this.x = x;
  3740. this.y = y;
  3741. this.z = z;
  3742. this.w = w;
  3743. }
  3744. /**
  3745. * Returns the string with the Vector4 coordinates.
  3746. */
  3747. Vector4.prototype.toString = function () {
  3748. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3749. };
  3750. /**
  3751. * Returns the string "Vector4".
  3752. */
  3753. Vector4.prototype.getClassName = function () {
  3754. return "Vector4";
  3755. };
  3756. /**
  3757. * Returns the Vector4 hash code.
  3758. */
  3759. Vector4.prototype.getHashCode = function () {
  3760. var hash = this.x || 0;
  3761. hash = (hash * 397) ^ (this.y || 0);
  3762. hash = (hash * 397) ^ (this.z || 0);
  3763. hash = (hash * 397) ^ (this.w || 0);
  3764. return hash;
  3765. };
  3766. // Operators
  3767. /**
  3768. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3769. */
  3770. Vector4.prototype.asArray = function () {
  3771. var result = new Array();
  3772. this.toArray(result, 0);
  3773. return result;
  3774. };
  3775. /**
  3776. * Populates the given array from the given index with the Vector4 coordinates.
  3777. * Returns the Vector4.
  3778. */
  3779. Vector4.prototype.toArray = function (array, index) {
  3780. if (index === undefined) {
  3781. index = 0;
  3782. }
  3783. array[index] = this.x;
  3784. array[index + 1] = this.y;
  3785. array[index + 2] = this.z;
  3786. array[index + 3] = this.w;
  3787. return this;
  3788. };
  3789. /**
  3790. * Adds the given vector to the current Vector4.
  3791. * Returns the updated Vector4.
  3792. */
  3793. Vector4.prototype.addInPlace = function (otherVector) {
  3794. this.x += otherVector.x;
  3795. this.y += otherVector.y;
  3796. this.z += otherVector.z;
  3797. this.w += otherVector.w;
  3798. return this;
  3799. };
  3800. /**
  3801. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3802. */
  3803. Vector4.prototype.add = function (otherVector) {
  3804. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3805. };
  3806. /**
  3807. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3808. * Returns the current Vector4.
  3809. */
  3810. Vector4.prototype.addToRef = function (otherVector, result) {
  3811. result.x = this.x + otherVector.x;
  3812. result.y = this.y + otherVector.y;
  3813. result.z = this.z + otherVector.z;
  3814. result.w = this.w + otherVector.w;
  3815. return this;
  3816. };
  3817. /**
  3818. * Subtract in place the given vector from the current Vector4.
  3819. * Returns the updated Vector4.
  3820. */
  3821. Vector4.prototype.subtractInPlace = function (otherVector) {
  3822. this.x -= otherVector.x;
  3823. this.y -= otherVector.y;
  3824. this.z -= otherVector.z;
  3825. this.w -= otherVector.w;
  3826. return this;
  3827. };
  3828. /**
  3829. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  3830. */
  3831. Vector4.prototype.subtract = function (otherVector) {
  3832. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3833. };
  3834. /**
  3835. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  3836. * Returns the current Vector4.
  3837. */
  3838. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3839. result.x = this.x - otherVector.x;
  3840. result.y = this.y - otherVector.y;
  3841. result.z = this.z - otherVector.z;
  3842. result.w = this.w - otherVector.w;
  3843. return this;
  3844. };
  3845. /**
  3846. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3847. */
  3848. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3849. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3850. };
  3851. /**
  3852. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3853. * Returns the current Vector4.
  3854. */
  3855. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3856. result.x = this.x - x;
  3857. result.y = this.y - y;
  3858. result.z = this.z - z;
  3859. result.w = this.w - w;
  3860. return this;
  3861. };
  3862. /**
  3863. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3864. */
  3865. Vector4.prototype.negate = function () {
  3866. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3867. };
  3868. /**
  3869. * Multiplies the current Vector4 coordinates by scale (float).
  3870. * Returns the updated Vector4.
  3871. */
  3872. Vector4.prototype.scaleInPlace = function (scale) {
  3873. this.x *= scale;
  3874. this.y *= scale;
  3875. this.z *= scale;
  3876. this.w *= scale;
  3877. return this;
  3878. };
  3879. /**
  3880. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  3881. */
  3882. Vector4.prototype.scale = function (scale) {
  3883. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  3884. };
  3885. /**
  3886. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  3887. * Returns the current Vector4.
  3888. */
  3889. Vector4.prototype.scaleToRef = function (scale, result) {
  3890. result.x = this.x * scale;
  3891. result.y = this.y * scale;
  3892. result.z = this.z * scale;
  3893. result.w = this.w * scale;
  3894. return this;
  3895. };
  3896. /**
  3897. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  3898. * @param scale defines the scale factor
  3899. * @param result defines the Vector4 object where to store the result
  3900. * @returns the unmodified current Vector4
  3901. */
  3902. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  3903. result.x += this.x * scale;
  3904. result.y += this.y * scale;
  3905. result.z += this.z * scale;
  3906. result.w += this.w * scale;
  3907. return this;
  3908. };
  3909. /**
  3910. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  3911. */
  3912. Vector4.prototype.equals = function (otherVector) {
  3913. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  3914. };
  3915. /**
  3916. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  3917. */
  3918. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3919. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3920. return otherVector
  3921. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  3922. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  3923. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  3924. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  3925. };
  3926. /**
  3927. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  3928. */
  3929. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  3930. return this.x === x && this.y === y && this.z === z && this.w === w;
  3931. };
  3932. /**
  3933. * Multiplies in place the current Vector4 by the given one.
  3934. * Returns the updated Vector4.
  3935. */
  3936. Vector4.prototype.multiplyInPlace = function (otherVector) {
  3937. this.x *= otherVector.x;
  3938. this.y *= otherVector.y;
  3939. this.z *= otherVector.z;
  3940. this.w *= otherVector.w;
  3941. return this;
  3942. };
  3943. /**
  3944. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  3945. */
  3946. Vector4.prototype.multiply = function (otherVector) {
  3947. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  3948. };
  3949. /**
  3950. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  3951. * Returns the current Vector4.
  3952. */
  3953. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  3954. result.x = this.x * otherVector.x;
  3955. result.y = this.y * otherVector.y;
  3956. result.z = this.z * otherVector.z;
  3957. result.w = this.w * otherVector.w;
  3958. return this;
  3959. };
  3960. /**
  3961. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  3962. */
  3963. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  3964. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  3965. };
  3966. /**
  3967. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  3968. */
  3969. Vector4.prototype.divide = function (otherVector) {
  3970. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  3971. };
  3972. /**
  3973. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  3974. * Returns the current Vector4.
  3975. */
  3976. Vector4.prototype.divideToRef = function (otherVector, result) {
  3977. result.x = this.x / otherVector.x;
  3978. result.y = this.y / otherVector.y;
  3979. result.z = this.z / otherVector.z;
  3980. result.w = this.w / otherVector.w;
  3981. return this;
  3982. };
  3983. /**
  3984. * Divides the current Vector3 coordinates by the given ones.
  3985. * @returns the updated Vector3.
  3986. */
  3987. Vector4.prototype.divideInPlace = function (otherVector) {
  3988. return this.divideToRef(otherVector, this);
  3989. };
  3990. /**
  3991. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  3992. * @param other defines the second operand
  3993. * @returns the current updated Vector4
  3994. */
  3995. Vector4.prototype.minimizeInPlace = function (other) {
  3996. if (other.x < this.x)
  3997. this.x = other.x;
  3998. if (other.y < this.y)
  3999. this.y = other.y;
  4000. if (other.z < this.z)
  4001. this.z = other.z;
  4002. if (other.w < this.w)
  4003. this.w = other.w;
  4004. return this;
  4005. };
  4006. /**
  4007. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4008. * @param other defines the second operand
  4009. * @returns the current updated Vector4
  4010. */
  4011. Vector4.prototype.maximizeInPlace = function (other) {
  4012. if (other.x > this.x)
  4013. this.x = other.x;
  4014. if (other.y > this.y)
  4015. this.y = other.y;
  4016. if (other.z > this.z)
  4017. this.z = other.z;
  4018. if (other.w > this.w)
  4019. this.w = other.w;
  4020. return this;
  4021. };
  4022. // Properties
  4023. /**
  4024. * Returns the Vector4 length (float).
  4025. */
  4026. Vector4.prototype.length = function () {
  4027. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4028. };
  4029. /**
  4030. * Returns the Vector4 squared length (float).
  4031. */
  4032. Vector4.prototype.lengthSquared = function () {
  4033. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4034. };
  4035. // Methods
  4036. /**
  4037. * Normalizes in place the Vector4.
  4038. * Returns the updated Vector4.
  4039. */
  4040. Vector4.prototype.normalize = function () {
  4041. var len = this.length();
  4042. if (len === 0)
  4043. return this;
  4044. var num = 1.0 / len;
  4045. this.x *= num;
  4046. this.y *= num;
  4047. this.z *= num;
  4048. this.w *= num;
  4049. return this;
  4050. };
  4051. /**
  4052. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4053. */
  4054. Vector4.prototype.toVector3 = function () {
  4055. return new Vector3(this.x, this.y, this.z);
  4056. };
  4057. /**
  4058. * Returns a new Vector4 copied from the current one.
  4059. */
  4060. Vector4.prototype.clone = function () {
  4061. return new Vector4(this.x, this.y, this.z, this.w);
  4062. };
  4063. /**
  4064. * Updates the current Vector4 with the given one coordinates.
  4065. * Returns the updated Vector4.
  4066. */
  4067. Vector4.prototype.copyFrom = function (source) {
  4068. this.x = source.x;
  4069. this.y = source.y;
  4070. this.z = source.z;
  4071. this.w = source.w;
  4072. return this;
  4073. };
  4074. /**
  4075. * Updates the current Vector4 coordinates with the given floats.
  4076. * Returns the updated Vector4.
  4077. */
  4078. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4079. this.x = x;
  4080. this.y = y;
  4081. this.z = z;
  4082. this.w = 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.set = function (x, y, z, w) {
  4090. return this.copyFromFloats(x, y, z, w);
  4091. };
  4092. // Statics
  4093. /**
  4094. * Returns a new Vector4 set from the starting index of the given array.
  4095. */
  4096. Vector4.FromArray = function (array, offset) {
  4097. if (!offset) {
  4098. offset = 0;
  4099. }
  4100. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4101. };
  4102. /**
  4103. * Updates the given vector "result" from the starting index of the given array.
  4104. */
  4105. Vector4.FromArrayToRef = function (array, offset, result) {
  4106. result.x = array[offset];
  4107. result.y = array[offset + 1];
  4108. result.z = array[offset + 2];
  4109. result.w = array[offset + 3];
  4110. };
  4111. /**
  4112. * Updates the given vector "result" from the starting index of the given Float32Array.
  4113. */
  4114. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4115. Vector4.FromArrayToRef(array, offset, result);
  4116. };
  4117. /**
  4118. * Updates the given vector "result" coordinates from the given floats.
  4119. */
  4120. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4121. result.x = x;
  4122. result.y = y;
  4123. result.z = z;
  4124. result.w = w;
  4125. };
  4126. /**
  4127. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4128. */
  4129. Vector4.Zero = function () {
  4130. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4131. };
  4132. /**
  4133. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4134. */
  4135. Vector4.One = function () {
  4136. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4137. };
  4138. /**
  4139. * Returns a new normalized Vector4 from the given one.
  4140. */
  4141. Vector4.Normalize = function (vector) {
  4142. var result = Vector4.Zero();
  4143. Vector4.NormalizeToRef(vector, result);
  4144. return result;
  4145. };
  4146. /**
  4147. * Updates the given vector "result" from the normalization of the given one.
  4148. */
  4149. Vector4.NormalizeToRef = function (vector, result) {
  4150. result.copyFrom(vector);
  4151. result.normalize();
  4152. };
  4153. Vector4.Minimize = function (left, right) {
  4154. var min = left.clone();
  4155. min.minimizeInPlace(right);
  4156. return min;
  4157. };
  4158. Vector4.Maximize = function (left, right) {
  4159. var max = left.clone();
  4160. max.maximizeInPlace(right);
  4161. return max;
  4162. };
  4163. /**
  4164. * Returns the distance (float) between the vectors "value1" and "value2".
  4165. */
  4166. Vector4.Distance = function (value1, value2) {
  4167. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4168. };
  4169. /**
  4170. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4171. */
  4172. Vector4.DistanceSquared = function (value1, value2) {
  4173. var x = value1.x - value2.x;
  4174. var y = value1.y - value2.y;
  4175. var z = value1.z - value2.z;
  4176. var w = value1.w - value2.w;
  4177. return (x * x) + (y * y) + (z * z) + (w * w);
  4178. };
  4179. /**
  4180. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4181. */
  4182. Vector4.Center = function (value1, value2) {
  4183. var center = value1.add(value2);
  4184. center.scaleInPlace(0.5);
  4185. return center;
  4186. };
  4187. /**
  4188. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4189. * This methods computes transformed normalized direction vectors only.
  4190. */
  4191. Vector4.TransformNormal = function (vector, transformation) {
  4192. var result = Vector4.Zero();
  4193. Vector4.TransformNormalToRef(vector, transformation, result);
  4194. return result;
  4195. };
  4196. /**
  4197. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4198. * This methods computes transformed normalized direction vectors only.
  4199. */
  4200. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4201. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4202. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4203. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4204. result.x = x;
  4205. result.y = y;
  4206. result.z = z;
  4207. result.w = vector.w;
  4208. };
  4209. /**
  4210. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4211. * This methods computes transformed normalized direction vectors only.
  4212. */
  4213. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4214. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4215. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4216. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4217. result.w = w;
  4218. };
  4219. return Vector4;
  4220. }());
  4221. BABYLON.Vector4 = Vector4;
  4222. var Size = /** @class */ (function () {
  4223. /**
  4224. * Creates a Size object from the given width and height (floats).
  4225. */
  4226. function Size(width, height) {
  4227. this.width = width;
  4228. this.height = height;
  4229. }
  4230. // Returns a string with the Size width and height.
  4231. Size.prototype.toString = function () {
  4232. return "{W: " + this.width + ", H: " + this.height + "}";
  4233. };
  4234. /**
  4235. * Returns the string "Size"
  4236. */
  4237. Size.prototype.getClassName = function () {
  4238. return "Size";
  4239. };
  4240. /**
  4241. * Returns the Size hash code.
  4242. */
  4243. Size.prototype.getHashCode = function () {
  4244. var hash = this.width || 0;
  4245. hash = (hash * 397) ^ (this.height || 0);
  4246. return hash;
  4247. };
  4248. /**
  4249. * Updates the current size from the given one.
  4250. * Returns the updated Size.
  4251. */
  4252. Size.prototype.copyFrom = function (src) {
  4253. this.width = src.width;
  4254. this.height = src.height;
  4255. };
  4256. /**
  4257. * Updates in place the current Size from the given floats.
  4258. * Returns the updated Size.
  4259. */
  4260. Size.prototype.copyFromFloats = function (width, height) {
  4261. this.width = width;
  4262. this.height = height;
  4263. return this;
  4264. };
  4265. /**
  4266. * Updates in place the current Size from the given floats.
  4267. * Returns the updated Size.
  4268. */
  4269. Size.prototype.set = function (width, height) {
  4270. return this.copyFromFloats(width, height);
  4271. };
  4272. /**
  4273. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4274. */
  4275. Size.prototype.multiplyByFloats = function (w, h) {
  4276. return new Size(this.width * w, this.height * h);
  4277. };
  4278. /**
  4279. * Returns a new Size copied from the given one.
  4280. */
  4281. Size.prototype.clone = function () {
  4282. return new Size(this.width, this.height);
  4283. };
  4284. /**
  4285. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4286. */
  4287. Size.prototype.equals = function (other) {
  4288. if (!other) {
  4289. return false;
  4290. }
  4291. return (this.width === other.width) && (this.height === other.height);
  4292. };
  4293. Object.defineProperty(Size.prototype, "surface", {
  4294. /**
  4295. * Returns the surface of the Size : width * height (float).
  4296. */
  4297. get: function () {
  4298. return this.width * this.height;
  4299. },
  4300. enumerable: true,
  4301. configurable: true
  4302. });
  4303. /**
  4304. * Returns a new Size set to (0.0, 0.0)
  4305. */
  4306. Size.Zero = function () {
  4307. return new Size(0.0, 0.0);
  4308. };
  4309. /**
  4310. * Returns a new Size set as the addition result of the current Size and the given one.
  4311. */
  4312. Size.prototype.add = function (otherSize) {
  4313. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4314. return r;
  4315. };
  4316. /**
  4317. * Returns a new Size set as the subtraction result of the given one from the current Size.
  4318. */
  4319. Size.prototype.subtract = function (otherSize) {
  4320. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4321. return r;
  4322. };
  4323. /**
  4324. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4325. */
  4326. Size.Lerp = function (start, end, amount) {
  4327. var w = start.width + ((end.width - start.width) * amount);
  4328. var h = start.height + ((end.height - start.height) * amount);
  4329. return new Size(w, h);
  4330. };
  4331. return Size;
  4332. }());
  4333. BABYLON.Size = Size;
  4334. /**
  4335. * Class used to store quaternion data
  4336. * @see https://en.wikipedia.org/wiki/Quaternion
  4337. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4338. */
  4339. var Quaternion = /** @class */ (function () {
  4340. /**
  4341. * Creates a new Quaternion from the given floats
  4342. * @param x defines the first component (0 by default)
  4343. * @param y defines the second component (0 by default)
  4344. * @param z defines the third component (0 by default)
  4345. * @param w defines the fourth component (1.0 by default)
  4346. */
  4347. function Quaternion(
  4348. /** defines the first component (0 by default) */
  4349. x,
  4350. /** defines the second component (0 by default) */
  4351. y,
  4352. /** defines the third component (0 by default) */
  4353. z,
  4354. /** defines the fourth component (1.0 by default) */
  4355. w) {
  4356. if (x === void 0) { x = 0.0; }
  4357. if (y === void 0) { y = 0.0; }
  4358. if (z === void 0) { z = 0.0; }
  4359. if (w === void 0) { w = 1.0; }
  4360. this.x = x;
  4361. this.y = y;
  4362. this.z = z;
  4363. this.w = w;
  4364. }
  4365. /**
  4366. * Gets a string representation for the current quaternion
  4367. * @returns a string with the Quaternion coordinates
  4368. */
  4369. Quaternion.prototype.toString = function () {
  4370. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4371. };
  4372. /**
  4373. * Gets the class name of the quaternion
  4374. * @returns the string "Quaternion"
  4375. */
  4376. Quaternion.prototype.getClassName = function () {
  4377. return "Quaternion";
  4378. };
  4379. /**
  4380. * Gets a hash code for this quaternion
  4381. * @returns the quaternion hash code
  4382. */
  4383. Quaternion.prototype.getHashCode = function () {
  4384. var hash = this.x || 0;
  4385. hash = (hash * 397) ^ (this.y || 0);
  4386. hash = (hash * 397) ^ (this.z || 0);
  4387. hash = (hash * 397) ^ (this.w || 0);
  4388. return hash;
  4389. };
  4390. /**
  4391. * Copy the quaternion to an array
  4392. * @returns a new array populated with 4 elements from the quaternion coordinates
  4393. */
  4394. Quaternion.prototype.asArray = function () {
  4395. return [this.x, this.y, this.z, this.w];
  4396. };
  4397. /**
  4398. * Check if two quaternions are equals
  4399. * @param otherQuaternion defines the second operand
  4400. * @return true if the current quaternion and the given one coordinates are strictly equals
  4401. */
  4402. Quaternion.prototype.equals = function (otherQuaternion) {
  4403. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4404. };
  4405. /**
  4406. * Clone the current quaternion
  4407. * @returns a new quaternion copied from the current one
  4408. */
  4409. Quaternion.prototype.clone = function () {
  4410. return new Quaternion(this.x, this.y, this.z, this.w);
  4411. };
  4412. /**
  4413. * Copy a quaternion to the current one
  4414. * @param other defines the other quaternion
  4415. * @returns the updated current quaternion
  4416. */
  4417. Quaternion.prototype.copyFrom = function (other) {
  4418. this.x = other.x;
  4419. this.y = other.y;
  4420. this.z = other.z;
  4421. this.w = other.w;
  4422. return this;
  4423. };
  4424. /**
  4425. * Updates the current quaternion with the given float coordinates
  4426. * @param x defines the x coordinate
  4427. * @param y defines the y coordinate
  4428. * @param z defines the z coordinate
  4429. * @param w defines the w coordinate
  4430. * @returns the updated current quaternion
  4431. */
  4432. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4433. this.x = x;
  4434. this.y = y;
  4435. this.z = z;
  4436. this.w = w;
  4437. return this;
  4438. };
  4439. /**
  4440. * Updates the current quaternion from the given float coordinates
  4441. * @param x defines the x coordinate
  4442. * @param y defines the y coordinate
  4443. * @param z defines the z coordinate
  4444. * @param w defines the w coordinate
  4445. * @returns the updated current quaternion
  4446. */
  4447. Quaternion.prototype.set = function (x, y, z, w) {
  4448. return this.copyFromFloats(x, y, z, w);
  4449. };
  4450. /**
  4451. * Adds two quaternions
  4452. * @param other defines the second operand
  4453. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4454. */
  4455. Quaternion.prototype.add = function (other) {
  4456. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4457. };
  4458. /**
  4459. * Add a quaternion to the current one
  4460. * @param other defines the quaternion to add
  4461. * @returns the current quaternion
  4462. */
  4463. Quaternion.prototype.addInPlace = function (other) {
  4464. this.x += other.x;
  4465. this.y += other.y;
  4466. this.z += other.z;
  4467. this.w += other.w;
  4468. return this;
  4469. };
  4470. /**
  4471. * Subtract two quaternions
  4472. * @param other defines the second operand
  4473. * @returns a new quaternion as the subtraction result of the given one from the current one
  4474. */
  4475. Quaternion.prototype.subtract = function (other) {
  4476. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4477. };
  4478. /**
  4479. * Multiplies the current quaternion by a scale factor
  4480. * @param value defines the scale factor
  4481. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4482. */
  4483. Quaternion.prototype.scale = function (value) {
  4484. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4485. };
  4486. /**
  4487. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4488. * @param scale defines the scale factor
  4489. * @param result defines the Quaternion object where to store the result
  4490. * @returns the unmodified current quaternion
  4491. */
  4492. Quaternion.prototype.scaleToRef = function (scale, result) {
  4493. result.x = this.x * scale;
  4494. result.y = this.y * scale;
  4495. result.z = this.z * scale;
  4496. result.w = this.w * scale;
  4497. return this;
  4498. };
  4499. /**
  4500. * Multiplies in place the current quaternion by a scale factor
  4501. * @param value defines the scale factor
  4502. * @returns the current modified quaternion
  4503. */
  4504. Quaternion.prototype.scaleInPlace = function (value) {
  4505. this.x *= value;
  4506. this.y *= value;
  4507. this.z *= value;
  4508. this.w *= value;
  4509. return this;
  4510. };
  4511. /**
  4512. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4513. * @param scale defines the scale factor
  4514. * @param result defines the Quaternion object where to store the result
  4515. * @returns the unmodified current quaternion
  4516. */
  4517. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4518. result.x += this.x * scale;
  4519. result.y += this.y * scale;
  4520. result.z += this.z * scale;
  4521. result.w += this.w * scale;
  4522. return this;
  4523. };
  4524. /**
  4525. * Multiplies two quaternions
  4526. * @param q1 defines the second operand
  4527. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4528. */
  4529. Quaternion.prototype.multiply = function (q1) {
  4530. var result = new Quaternion(0, 0, 0, 1.0);
  4531. this.multiplyToRef(q1, result);
  4532. return result;
  4533. };
  4534. /**
  4535. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4536. * @param q1 defines the second operand
  4537. * @param result defines the target quaternion
  4538. * @returns the current quaternion
  4539. */
  4540. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4541. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4542. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4543. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4544. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4545. result.copyFromFloats(x, y, z, w);
  4546. return this;
  4547. };
  4548. /**
  4549. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4550. * @param q1 defines the second operand
  4551. * @returns the currentupdated quaternion
  4552. */
  4553. Quaternion.prototype.multiplyInPlace = function (q1) {
  4554. this.multiplyToRef(q1, this);
  4555. return this;
  4556. };
  4557. /**
  4558. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4559. * @param ref defines the target quaternion
  4560. * @returns the current quaternion
  4561. */
  4562. Quaternion.prototype.conjugateToRef = function (ref) {
  4563. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4564. return this;
  4565. };
  4566. /**
  4567. * Conjugates in place (1-q) the current quaternion
  4568. * @returns the current updated quaternion
  4569. */
  4570. Quaternion.prototype.conjugateInPlace = function () {
  4571. this.x *= -1;
  4572. this.y *= -1;
  4573. this.z *= -1;
  4574. return this;
  4575. };
  4576. /**
  4577. * Conjugates in place (1-q) the current quaternion
  4578. * @returns a new quaternion
  4579. */
  4580. Quaternion.prototype.conjugate = function () {
  4581. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4582. return result;
  4583. };
  4584. /**
  4585. * Gets length of current quaternion
  4586. * @returns the quaternion length (float)
  4587. */
  4588. Quaternion.prototype.length = function () {
  4589. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4590. };
  4591. /**
  4592. * Normalize in place the current quaternion
  4593. * @returns the current updated quaternion
  4594. */
  4595. Quaternion.prototype.normalize = function () {
  4596. var length = 1.0 / this.length();
  4597. this.x *= length;
  4598. this.y *= length;
  4599. this.z *= length;
  4600. this.w *= length;
  4601. return this;
  4602. };
  4603. /**
  4604. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4605. * @param order is a reserved parameter and is ignore for now
  4606. * @returns a new Vector3 containing the Euler angles
  4607. */
  4608. Quaternion.prototype.toEulerAngles = function (order) {
  4609. if (order === void 0) { order = "YZX"; }
  4610. var result = Vector3.Zero();
  4611. this.toEulerAnglesToRef(result, order);
  4612. return result;
  4613. };
  4614. /**
  4615. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4616. * @param result defines the vector which will be filled with the Euler angles
  4617. * @param order is a reserved parameter and is ignore for now
  4618. * @returns the current unchanged quaternion
  4619. */
  4620. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4621. if (order === void 0) { order = "YZX"; }
  4622. var qz = this.z;
  4623. var qx = this.x;
  4624. var qy = this.y;
  4625. var qw = this.w;
  4626. var sqw = qw * qw;
  4627. var sqz = qz * qz;
  4628. var sqx = qx * qx;
  4629. var sqy = qy * qy;
  4630. var zAxisY = qy * qz - qx * qw;
  4631. var limit = .4999999;
  4632. if (zAxisY < -limit) {
  4633. result.y = 2 * Math.atan2(qy, qw);
  4634. result.x = Math.PI / 2;
  4635. result.z = 0;
  4636. }
  4637. else if (zAxisY > limit) {
  4638. result.y = 2 * Math.atan2(qy, qw);
  4639. result.x = -Math.PI / 2;
  4640. result.z = 0;
  4641. }
  4642. else {
  4643. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4644. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4645. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4646. }
  4647. return this;
  4648. };
  4649. /**
  4650. * Updates the given rotation matrix with the current quaternion values
  4651. * @param result defines the target matrix
  4652. * @returns the current unchanged quaternion
  4653. */
  4654. Quaternion.prototype.toRotationMatrix = function (result) {
  4655. var xx = this.x * this.x;
  4656. var yy = this.y * this.y;
  4657. var zz = this.z * this.z;
  4658. var xy = this.x * this.y;
  4659. var zw = this.z * this.w;
  4660. var zx = this.z * this.x;
  4661. var yw = this.y * this.w;
  4662. var yz = this.y * this.z;
  4663. var xw = this.x * this.w;
  4664. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4665. result.m[1] = 2.0 * (xy + zw);
  4666. result.m[2] = 2.0 * (zx - yw);
  4667. result.m[3] = 0;
  4668. result.m[4] = 2.0 * (xy - zw);
  4669. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4670. result.m[6] = 2.0 * (yz + xw);
  4671. result.m[7] = 0;
  4672. result.m[8] = 2.0 * (zx + yw);
  4673. result.m[9] = 2.0 * (yz - xw);
  4674. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4675. result.m[11] = 0;
  4676. result.m[12] = 0;
  4677. result.m[13] = 0;
  4678. result.m[14] = 0;
  4679. result.m[15] = 1.0;
  4680. result._markAsUpdated();
  4681. return this;
  4682. };
  4683. /**
  4684. * Updates the current quaternion from the given rotation matrix values
  4685. * @param matrix defines the source matrix
  4686. * @returns the current updated quaternion
  4687. */
  4688. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4689. Quaternion.FromRotationMatrixToRef(matrix, this);
  4690. return this;
  4691. };
  4692. // Statics
  4693. /**
  4694. * Creates a new quaternion from a rotation matrix
  4695. * @param matrix defines the source matrix
  4696. * @returns a new quaternion created from the given rotation matrix values
  4697. */
  4698. Quaternion.FromRotationMatrix = function (matrix) {
  4699. var result = new Quaternion();
  4700. Quaternion.FromRotationMatrixToRef(matrix, result);
  4701. return result;
  4702. };
  4703. /**
  4704. * Updates the given quaternion with the given rotation matrix values
  4705. * @param matrix defines the source matrix
  4706. * @param result defines the target quaternion
  4707. */
  4708. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4709. var data = matrix.m;
  4710. var m11 = data[0], m12 = data[4], m13 = data[8];
  4711. var m21 = data[1], m22 = data[5], m23 = data[9];
  4712. var m31 = data[2], m32 = data[6], m33 = data[10];
  4713. var trace = m11 + m22 + m33;
  4714. var s;
  4715. if (trace > 0) {
  4716. s = 0.5 / Math.sqrt(trace + 1.0);
  4717. result.w = 0.25 / s;
  4718. result.x = (m32 - m23) * s;
  4719. result.y = (m13 - m31) * s;
  4720. result.z = (m21 - m12) * s;
  4721. }
  4722. else if (m11 > m22 && m11 > m33) {
  4723. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4724. result.w = (m32 - m23) / s;
  4725. result.x = 0.25 * s;
  4726. result.y = (m12 + m21) / s;
  4727. result.z = (m13 + m31) / s;
  4728. }
  4729. else if (m22 > m33) {
  4730. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4731. result.w = (m13 - m31) / s;
  4732. result.x = (m12 + m21) / s;
  4733. result.y = 0.25 * s;
  4734. result.z = (m23 + m32) / s;
  4735. }
  4736. else {
  4737. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4738. result.w = (m21 - m12) / s;
  4739. result.x = (m13 + m31) / s;
  4740. result.y = (m23 + m32) / s;
  4741. result.z = 0.25 * s;
  4742. }
  4743. };
  4744. /**
  4745. * Returns the dot product (float) between the quaternions "left" and "right"
  4746. * @param left defines the left operand
  4747. * @param right defines the right operand
  4748. * @returns the dot product
  4749. */
  4750. Quaternion.Dot = function (left, right) {
  4751. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  4752. };
  4753. /**
  4754. * Checks if the two quaternions are close to each other
  4755. * @param quat0 defines the first quaternion to check
  4756. * @param quat1 defines the second quaternion to check
  4757. * @returns true if the two quaternions are close to each other
  4758. */
  4759. Quaternion.AreClose = function (quat0, quat1) {
  4760. var dot = Quaternion.Dot(quat0, quat1);
  4761. return dot >= 0;
  4762. };
  4763. /**
  4764. * Creates an empty quaternion
  4765. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4766. */
  4767. Quaternion.Zero = function () {
  4768. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4769. };
  4770. /**
  4771. * Inverse a given quaternion
  4772. * @param q defines the source quaternion
  4773. * @returns a new quaternion as the inverted current quaternion
  4774. */
  4775. Quaternion.Inverse = function (q) {
  4776. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4777. };
  4778. /**
  4779. * Creates an identity quaternion
  4780. * @returns the identity quaternion
  4781. */
  4782. Quaternion.Identity = function () {
  4783. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4784. };
  4785. /**
  4786. * Gets a boolean indicating if the given quaternion is identity
  4787. * @param quaternion defines the quaternion to check
  4788. * @returns true if the quaternion is identity
  4789. */
  4790. Quaternion.IsIdentity = function (quaternion) {
  4791. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4792. };
  4793. /**
  4794. * Creates a quaternion from a rotation around an axis
  4795. * @param axis defines the axis to use
  4796. * @param angle defines the angle to use
  4797. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4798. */
  4799. Quaternion.RotationAxis = function (axis, angle) {
  4800. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4801. };
  4802. /**
  4803. * Creates a rotation around an axis and stores it into the given quaternion
  4804. * @param axis defines the axis to use
  4805. * @param angle defines the angle to use
  4806. * @param result defines the target quaternion
  4807. * @returns the target quaternion
  4808. */
  4809. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4810. var sin = Math.sin(angle / 2);
  4811. axis.normalize();
  4812. result.w = Math.cos(angle / 2);
  4813. result.x = axis.x * sin;
  4814. result.y = axis.y * sin;
  4815. result.z = axis.z * sin;
  4816. return result;
  4817. };
  4818. /**
  4819. * Creates a new quaternion from data stored into an array
  4820. * @param array defines the data source
  4821. * @param offset defines the offset in the source array where the data starts
  4822. * @returns a new quaternion
  4823. */
  4824. Quaternion.FromArray = function (array, offset) {
  4825. if (!offset) {
  4826. offset = 0;
  4827. }
  4828. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4829. };
  4830. /**
  4831. * Creates a new quaternion from the given Euler float angles (y, x, z)
  4832. * @param yaw defines the rotation around Y axis
  4833. * @param pitch defines the rotation around X axis
  4834. * @param roll defines the rotation around Z axis
  4835. * @returns the new quaternion
  4836. */
  4837. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4838. var q = new Quaternion();
  4839. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4840. return q;
  4841. };
  4842. /**
  4843. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  4844. * @param yaw defines the rotation around Y axis
  4845. * @param pitch defines the rotation around X axis
  4846. * @param roll defines the rotation around Z axis
  4847. * @param result defines the target quaternion
  4848. */
  4849. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4850. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4851. var halfRoll = roll * 0.5;
  4852. var halfPitch = pitch * 0.5;
  4853. var halfYaw = yaw * 0.5;
  4854. var sinRoll = Math.sin(halfRoll);
  4855. var cosRoll = Math.cos(halfRoll);
  4856. var sinPitch = Math.sin(halfPitch);
  4857. var cosPitch = Math.cos(halfPitch);
  4858. var sinYaw = Math.sin(halfYaw);
  4859. var cosYaw = Math.cos(halfYaw);
  4860. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4861. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4862. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4863. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4864. };
  4865. /**
  4866. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  4867. * @param alpha defines the rotation around first axis
  4868. * @param beta defines the rotation around second axis
  4869. * @param gamma defines the rotation around third axis
  4870. * @returns the new quaternion
  4871. */
  4872. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4873. var result = new Quaternion();
  4874. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  4875. return result;
  4876. };
  4877. /**
  4878. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  4879. * @param alpha defines the rotation around first axis
  4880. * @param beta defines the rotation around second axis
  4881. * @param gamma defines the rotation around third axis
  4882. * @param result defines the target quaternion
  4883. */
  4884. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  4885. // Produces a quaternion from Euler angles in the z-x-z orientation
  4886. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  4887. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  4888. var halfBeta = beta * 0.5;
  4889. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4890. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  4891. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4892. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  4893. };
  4894. /**
  4895. * 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)
  4896. * @param axis1 defines the first axis
  4897. * @param axis2 defines the second axis
  4898. * @param axis3 defines the third axis
  4899. * @returns the new quaternion
  4900. */
  4901. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  4902. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  4903. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  4904. return quat;
  4905. };
  4906. /**
  4907. * 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
  4908. * @param axis1 defines the first axis
  4909. * @param axis2 defines the second axis
  4910. * @param axis3 defines the third axis
  4911. * @param ref defines the target quaternion
  4912. */
  4913. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  4914. var rotMat = MathTmp.Matrix[0];
  4915. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  4916. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  4917. };
  4918. /**
  4919. * Interpolates between two quaternions
  4920. * @param left defines first quaternion
  4921. * @param right defines second quaternion
  4922. * @param amount defines the gradient to use
  4923. * @returns the new interpolated quaternion
  4924. */
  4925. Quaternion.Slerp = function (left, right, amount) {
  4926. var result = Quaternion.Identity();
  4927. Quaternion.SlerpToRef(left, right, amount, result);
  4928. return result;
  4929. };
  4930. /**
  4931. * Interpolates between two quaternions and stores it into a target quaternion
  4932. * @param left defines first quaternion
  4933. * @param right defines second quaternion
  4934. * @param amount defines the gradient to use
  4935. * @param result defines the target quaternion
  4936. */
  4937. Quaternion.SlerpToRef = function (left, right, amount, result) {
  4938. var num2;
  4939. var num3;
  4940. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  4941. var flag = false;
  4942. if (num4 < 0) {
  4943. flag = true;
  4944. num4 = -num4;
  4945. }
  4946. if (num4 > 0.999999) {
  4947. num3 = 1 - amount;
  4948. num2 = flag ? -amount : amount;
  4949. }
  4950. else {
  4951. var num5 = Math.acos(num4);
  4952. var num6 = (1.0 / Math.sin(num5));
  4953. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  4954. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  4955. }
  4956. result.x = (num3 * left.x) + (num2 * right.x);
  4957. result.y = (num3 * left.y) + (num2 * right.y);
  4958. result.z = (num3 * left.z) + (num2 * right.z);
  4959. result.w = (num3 * left.w) + (num2 * right.w);
  4960. };
  4961. /**
  4962. * Interpolate between two quaternions using Hermite interpolation
  4963. * @param value1 defines first quaternion
  4964. * @param tangent1 defines the incoming tangent
  4965. * @param value2 defines second quaternion
  4966. * @param tangent2 defines the outgoing tangent
  4967. * @param amount defines the target quaternion
  4968. * @returns the new interpolated quaternion
  4969. */
  4970. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4971. var squared = amount * amount;
  4972. var cubed = amount * squared;
  4973. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4974. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4975. var part3 = (cubed - (2.0 * squared)) + amount;
  4976. var part4 = cubed - squared;
  4977. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  4978. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  4979. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  4980. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  4981. return new Quaternion(x, y, z, w);
  4982. };
  4983. return Quaternion;
  4984. }());
  4985. BABYLON.Quaternion = Quaternion;
  4986. /**
  4987. * Class used to store matrix data (4x4)
  4988. */
  4989. var Matrix = /** @class */ (function () {
  4990. /**
  4991. * Creates an empty matrix (filled with zeros)
  4992. */
  4993. function Matrix() {
  4994. this._isIdentity = false;
  4995. this._isIdentityDirty = true;
  4996. /**
  4997. * Gets or sets the internal data of the matrix
  4998. */
  4999. this.m = new Float32Array(16);
  5000. this._markAsUpdated();
  5001. }
  5002. /** @hidden */
  5003. Matrix.prototype._markAsUpdated = function () {
  5004. this.updateFlag = Matrix._updateFlagSeed++;
  5005. this._isIdentityDirty = true;
  5006. };
  5007. // Properties
  5008. /**
  5009. * Check if the current matrix is indentity
  5010. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5011. * @returns true is the matrix is the identity matrix
  5012. */
  5013. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5014. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5015. if (this._isIdentityDirty) {
  5016. this._isIdentityDirty = false;
  5017. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5018. this._isIdentity = false;
  5019. }
  5020. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5021. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5022. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5023. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5024. this._isIdentity = false;
  5025. }
  5026. else {
  5027. this._isIdentity = true;
  5028. }
  5029. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5030. this._isIdentity = false;
  5031. }
  5032. }
  5033. return this._isIdentity;
  5034. };
  5035. /**
  5036. * Gets the determinant of the matrix
  5037. * @returns the matrix determinant
  5038. */
  5039. Matrix.prototype.determinant = function () {
  5040. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5041. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5042. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5043. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5044. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5045. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5046. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5047. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5048. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5049. };
  5050. // Methods
  5051. /**
  5052. * Returns the matrix as a Float32Array
  5053. * @returns the matrix underlying array
  5054. */
  5055. Matrix.prototype.toArray = function () {
  5056. return this.m;
  5057. };
  5058. /**
  5059. * Returns the matrix as a Float32Array
  5060. * @returns the matrix underlying array.
  5061. */
  5062. Matrix.prototype.asArray = function () {
  5063. return this.toArray();
  5064. };
  5065. /**
  5066. * Inverts the current matrix in place
  5067. * @returns the current inverted matrix
  5068. */
  5069. Matrix.prototype.invert = function () {
  5070. this.invertToRef(this);
  5071. return this;
  5072. };
  5073. /**
  5074. * Sets all the matrix elements to zero
  5075. * @returns the current matrix
  5076. */
  5077. Matrix.prototype.reset = function () {
  5078. for (var index = 0; index < 16; index++) {
  5079. this.m[index] = 0.0;
  5080. }
  5081. this._markAsUpdated();
  5082. return this;
  5083. };
  5084. /**
  5085. * Adds the current matrix with a second one
  5086. * @param other defines the matrix to add
  5087. * @returns a new matrix as the addition of the current matrix and the given one
  5088. */
  5089. Matrix.prototype.add = function (other) {
  5090. var result = new Matrix();
  5091. this.addToRef(other, result);
  5092. return result;
  5093. };
  5094. /**
  5095. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5096. * @param other defines the matrix to add
  5097. * @param result defines the target matrix
  5098. * @returns the current matrix
  5099. */
  5100. Matrix.prototype.addToRef = function (other, result) {
  5101. for (var index = 0; index < 16; index++) {
  5102. result.m[index] = this.m[index] + other.m[index];
  5103. }
  5104. result._markAsUpdated();
  5105. return this;
  5106. };
  5107. /**
  5108. * Adds in place the given matrix to the current matrix
  5109. * @param other defines the second operand
  5110. * @returns the current updated matrix
  5111. */
  5112. Matrix.prototype.addToSelf = function (other) {
  5113. for (var index = 0; index < 16; index++) {
  5114. this.m[index] += other.m[index];
  5115. }
  5116. this._markAsUpdated();
  5117. return this;
  5118. };
  5119. /**
  5120. * Sets the given matrix to the current inverted Matrix
  5121. * @param other defines the target matrix
  5122. * @returns the unmodified current matrix
  5123. */
  5124. Matrix.prototype.invertToRef = function (other) {
  5125. var l1 = this.m[0];
  5126. var l2 = this.m[1];
  5127. var l3 = this.m[2];
  5128. var l4 = this.m[3];
  5129. var l5 = this.m[4];
  5130. var l6 = this.m[5];
  5131. var l7 = this.m[6];
  5132. var l8 = this.m[7];
  5133. var l9 = this.m[8];
  5134. var l10 = this.m[9];
  5135. var l11 = this.m[10];
  5136. var l12 = this.m[11];
  5137. var l13 = this.m[12];
  5138. var l14 = this.m[13];
  5139. var l15 = this.m[14];
  5140. var l16 = this.m[15];
  5141. var l17 = (l11 * l16) - (l12 * l15);
  5142. var l18 = (l10 * l16) - (l12 * l14);
  5143. var l19 = (l10 * l15) - (l11 * l14);
  5144. var l20 = (l9 * l16) - (l12 * l13);
  5145. var l21 = (l9 * l15) - (l11 * l13);
  5146. var l22 = (l9 * l14) - (l10 * l13);
  5147. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5148. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5149. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5150. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5151. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5152. var l28 = (l7 * l16) - (l8 * l15);
  5153. var l29 = (l6 * l16) - (l8 * l14);
  5154. var l30 = (l6 * l15) - (l7 * l14);
  5155. var l31 = (l5 * l16) - (l8 * l13);
  5156. var l32 = (l5 * l15) - (l7 * l13);
  5157. var l33 = (l5 * l14) - (l6 * l13);
  5158. var l34 = (l7 * l12) - (l8 * l11);
  5159. var l35 = (l6 * l12) - (l8 * l10);
  5160. var l36 = (l6 * l11) - (l7 * l10);
  5161. var l37 = (l5 * l12) - (l8 * l9);
  5162. var l38 = (l5 * l11) - (l7 * l9);
  5163. var l39 = (l5 * l10) - (l6 * l9);
  5164. other.m[0] = l23 * l27;
  5165. other.m[4] = l24 * l27;
  5166. other.m[8] = l25 * l27;
  5167. other.m[12] = l26 * l27;
  5168. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5169. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5170. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5171. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5172. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5173. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5174. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5175. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5176. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5177. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5178. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5179. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5180. other._markAsUpdated();
  5181. return this;
  5182. };
  5183. /**
  5184. * Inserts the translation vector (using 3 floats) in the current matrix
  5185. * @param x defines the 1st component of the translation
  5186. * @param y defines the 2nd component of the translation
  5187. * @param z defines the 3rd component of the translation
  5188. * @returns the current updated matrix
  5189. */
  5190. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5191. this.m[12] = x;
  5192. this.m[13] = y;
  5193. this.m[14] = z;
  5194. this._markAsUpdated();
  5195. return this;
  5196. };
  5197. /**
  5198. * Inserts the translation vector in the current matrix
  5199. * @param vector3 defines the translation to insert
  5200. * @returns the current updated matrix
  5201. */
  5202. Matrix.prototype.setTranslation = function (vector3) {
  5203. this.m[12] = vector3.x;
  5204. this.m[13] = vector3.y;
  5205. this.m[14] = vector3.z;
  5206. this._markAsUpdated();
  5207. return this;
  5208. };
  5209. /**
  5210. * Gets the translation value of the current matrix
  5211. * @returns a new Vector3 as the extracted translation from the matrix
  5212. */
  5213. Matrix.prototype.getTranslation = function () {
  5214. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5215. };
  5216. /**
  5217. * Fill a Vector3 with the extracted translation from the matrix
  5218. * @param result defines the Vector3 where to store the translation
  5219. * @returns the current matrix
  5220. */
  5221. Matrix.prototype.getTranslationToRef = function (result) {
  5222. result.x = this.m[12];
  5223. result.y = this.m[13];
  5224. result.z = this.m[14];
  5225. return this;
  5226. };
  5227. /**
  5228. * Remove rotation and scaling part from the matrix
  5229. * @returns the updated matrix
  5230. */
  5231. Matrix.prototype.removeRotationAndScaling = function () {
  5232. this.setRowFromFloats(0, 1, 0, 0, 0);
  5233. this.setRowFromFloats(1, 0, 1, 0, 0);
  5234. this.setRowFromFloats(2, 0, 0, 1, 0);
  5235. return this;
  5236. };
  5237. /**
  5238. * Multiply two matrices
  5239. * @param other defines the second operand
  5240. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5241. */
  5242. Matrix.prototype.multiply = function (other) {
  5243. var result = new Matrix();
  5244. this.multiplyToRef(other, result);
  5245. return result;
  5246. };
  5247. /**
  5248. * Copy the current matrix from the given one
  5249. * @param other defines the source matrix
  5250. * @returns the current updated matrix
  5251. */
  5252. Matrix.prototype.copyFrom = function (other) {
  5253. for (var index = 0; index < 16; index++) {
  5254. this.m[index] = other.m[index];
  5255. }
  5256. this._markAsUpdated();
  5257. return this;
  5258. };
  5259. /**
  5260. * Populates the given array from the starting index with the current matrix values
  5261. * @param array defines the target array
  5262. * @param offset defines the offset in the target array where to start storing values
  5263. * @returns the current matrix
  5264. */
  5265. Matrix.prototype.copyToArray = function (array, offset) {
  5266. if (offset === void 0) { offset = 0; }
  5267. for (var index = 0; index < 16; index++) {
  5268. array[offset + index] = this.m[index];
  5269. }
  5270. return this;
  5271. };
  5272. /**
  5273. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5274. * @param other defines the second operand
  5275. * @param result defines the matrix where to store the multiplication
  5276. * @returns the current matrix
  5277. */
  5278. Matrix.prototype.multiplyToRef = function (other, result) {
  5279. this.multiplyToArray(other, result.m, 0);
  5280. result._markAsUpdated();
  5281. return this;
  5282. };
  5283. /**
  5284. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5285. * @param other defines the second operand
  5286. * @param result defines the array where to store the multiplication
  5287. * @param offset defines the offset in the target array where to start storing values
  5288. * @returns the current matrix
  5289. */
  5290. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5291. var tm0 = this.m[0];
  5292. var tm1 = this.m[1];
  5293. var tm2 = this.m[2];
  5294. var tm3 = this.m[3];
  5295. var tm4 = this.m[4];
  5296. var tm5 = this.m[5];
  5297. var tm6 = this.m[6];
  5298. var tm7 = this.m[7];
  5299. var tm8 = this.m[8];
  5300. var tm9 = this.m[9];
  5301. var tm10 = this.m[10];
  5302. var tm11 = this.m[11];
  5303. var tm12 = this.m[12];
  5304. var tm13 = this.m[13];
  5305. var tm14 = this.m[14];
  5306. var tm15 = this.m[15];
  5307. var om0 = other.m[0];
  5308. var om1 = other.m[1];
  5309. var om2 = other.m[2];
  5310. var om3 = other.m[3];
  5311. var om4 = other.m[4];
  5312. var om5 = other.m[5];
  5313. var om6 = other.m[6];
  5314. var om7 = other.m[7];
  5315. var om8 = other.m[8];
  5316. var om9 = other.m[9];
  5317. var om10 = other.m[10];
  5318. var om11 = other.m[11];
  5319. var om12 = other.m[12];
  5320. var om13 = other.m[13];
  5321. var om14 = other.m[14];
  5322. var om15 = other.m[15];
  5323. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5324. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5325. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5326. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5327. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5328. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5329. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5330. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5331. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5332. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5333. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5334. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5335. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5336. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5337. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5338. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5339. return this;
  5340. };
  5341. /**
  5342. * Check equality between this matrix and a second one
  5343. * @param value defines the second matrix to compare
  5344. * @returns true is the current matrix and the given one values are strictly equal
  5345. */
  5346. Matrix.prototype.equals = function (value) {
  5347. return value &&
  5348. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5349. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5350. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5351. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5352. };
  5353. /**
  5354. * Clone the current matrix
  5355. * @returns a new matrix from the current matrix
  5356. */
  5357. Matrix.prototype.clone = function () {
  5358. 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]);
  5359. };
  5360. /**
  5361. * Returns the name of the current matrix class
  5362. * @returns the string "Matrix"
  5363. */
  5364. Matrix.prototype.getClassName = function () {
  5365. return "Matrix";
  5366. };
  5367. /**
  5368. * Gets the hash code of the current matrix
  5369. * @returns the hash code
  5370. */
  5371. Matrix.prototype.getHashCode = function () {
  5372. var hash = this.m[0] || 0;
  5373. for (var i = 1; i < 16; i++) {
  5374. hash = (hash * 397) ^ (this.m[i] || 0);
  5375. }
  5376. return hash;
  5377. };
  5378. /**
  5379. * Decomposes the current Matrix into a translation, rotation and scaling components
  5380. * @param scale defines the scale vector3 given as a reference to update
  5381. * @param rotation defines the rotation quaternion given as a reference to update
  5382. * @param translation defines the translation vector3 given as a reference to update
  5383. * @returns true if operation was successful
  5384. */
  5385. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5386. if (translation) {
  5387. translation.x = this.m[12];
  5388. translation.y = this.m[13];
  5389. translation.z = this.m[14];
  5390. }
  5391. scale = scale || MathTmp.Vector3[0];
  5392. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5393. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5394. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5395. if (this.determinant() <= 0) {
  5396. scale.y *= -1;
  5397. }
  5398. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5399. if (rotation) {
  5400. rotation.x = 0;
  5401. rotation.y = 0;
  5402. rotation.z = 0;
  5403. rotation.w = 1;
  5404. }
  5405. return false;
  5406. }
  5407. if (rotation) {
  5408. 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]);
  5409. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5410. }
  5411. return true;
  5412. };
  5413. /**
  5414. * Gets specific row of the matrix
  5415. * @param index defines the number of the row to get
  5416. * @returns the index-th row of the current matrix as a new Vector4
  5417. */
  5418. Matrix.prototype.getRow = function (index) {
  5419. if (index < 0 || index > 3) {
  5420. return null;
  5421. }
  5422. var i = index * 4;
  5423. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5424. };
  5425. /**
  5426. * Sets the index-th row of the current matrix to the vector4 values
  5427. * @param index defines the number of the row to set
  5428. * @param row defines the target vector4
  5429. * @returns the updated current matrix
  5430. */
  5431. Matrix.prototype.setRow = function (index, row) {
  5432. if (index < 0 || index > 3) {
  5433. return this;
  5434. }
  5435. var i = index * 4;
  5436. this.m[i + 0] = row.x;
  5437. this.m[i + 1] = row.y;
  5438. this.m[i + 2] = row.z;
  5439. this.m[i + 3] = row.w;
  5440. this._markAsUpdated();
  5441. return this;
  5442. };
  5443. /**
  5444. * Compute the transpose of the matrix
  5445. * @returns the new transposed matrix
  5446. */
  5447. Matrix.prototype.transpose = function () {
  5448. return Matrix.Transpose(this);
  5449. };
  5450. /**
  5451. * Compute the transpose of the matrix and store it in a given matrix
  5452. * @param result defines the target matrix
  5453. * @returns the current matrix
  5454. */
  5455. Matrix.prototype.transposeToRef = function (result) {
  5456. Matrix.TransposeToRef(this, result);
  5457. return this;
  5458. };
  5459. /**
  5460. * Sets the index-th row of the current matrix with the given 4 x float values
  5461. * @param index defines the row index
  5462. * @param x defines the x component to set
  5463. * @param y defines the y component to set
  5464. * @param z defines the z component to set
  5465. * @param w defines the w component to set
  5466. * @returns the updated current matrix
  5467. */
  5468. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5469. if (index < 0 || index > 3) {
  5470. return this;
  5471. }
  5472. var i = index * 4;
  5473. this.m[i + 0] = x;
  5474. this.m[i + 1] = y;
  5475. this.m[i + 2] = z;
  5476. this.m[i + 3] = w;
  5477. this._markAsUpdated();
  5478. return this;
  5479. };
  5480. /**
  5481. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5482. * @param scale defines the scale factor
  5483. * @returns a new matrix
  5484. */
  5485. Matrix.prototype.scale = function (scale) {
  5486. var result = new Matrix();
  5487. this.scaleToRef(scale, result);
  5488. return result;
  5489. };
  5490. /**
  5491. * Scale the current matrix values by a factor to a given result matrix
  5492. * @param scale defines the scale factor
  5493. * @param result defines the matrix to store the result
  5494. * @returns the current matrix
  5495. */
  5496. Matrix.prototype.scaleToRef = function (scale, result) {
  5497. for (var index = 0; index < 16; index++) {
  5498. result.m[index] = this.m[index] * scale;
  5499. }
  5500. result._markAsUpdated();
  5501. return this;
  5502. };
  5503. /**
  5504. * Scale the current matrix values by a factor and add the result to a given matrix
  5505. * @param scale defines the scale factor
  5506. * @param result defines the Matrix to store the result
  5507. * @returns the current matrix
  5508. */
  5509. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5510. for (var index = 0; index < 16; index++) {
  5511. result.m[index] += this.m[index] * scale;
  5512. }
  5513. result._markAsUpdated();
  5514. return this;
  5515. };
  5516. /**
  5517. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5518. * @param ref matrix to store the result
  5519. */
  5520. Matrix.prototype.toNormalMatrix = function (ref) {
  5521. this.invertToRef(ref);
  5522. ref.transpose();
  5523. var m = ref.m;
  5524. 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);
  5525. };
  5526. /**
  5527. * Gets only rotation part of the current matrix
  5528. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5529. */
  5530. Matrix.prototype.getRotationMatrix = function () {
  5531. var result = Matrix.Identity();
  5532. this.getRotationMatrixToRef(result);
  5533. return result;
  5534. };
  5535. /**
  5536. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5537. * @param result defines the target matrix to store data to
  5538. * @returns the current matrix
  5539. */
  5540. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5541. var m = this.m;
  5542. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5543. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5544. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5545. if (this.determinant() <= 0) {
  5546. sy *= -1;
  5547. }
  5548. if (sx === 0 || sy === 0 || sz === 0) {
  5549. Matrix.IdentityToRef(result);
  5550. }
  5551. else {
  5552. 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);
  5553. }
  5554. return this;
  5555. };
  5556. // Statics
  5557. /**
  5558. * Creates a matrix from an array
  5559. * @param array defines the source array
  5560. * @param offset defines an offset in the source array
  5561. * @returns a new Matrix set from the starting index of the given array
  5562. */
  5563. Matrix.FromArray = function (array, offset) {
  5564. var result = new Matrix();
  5565. if (!offset) {
  5566. offset = 0;
  5567. }
  5568. Matrix.FromArrayToRef(array, offset, result);
  5569. return result;
  5570. };
  5571. /**
  5572. * Copy the content of an array into a given matrix
  5573. * @param array defines the source array
  5574. * @param offset defines an offset in the source array
  5575. * @param result defines the target matrix
  5576. */
  5577. Matrix.FromArrayToRef = function (array, offset, result) {
  5578. for (var index = 0; index < 16; index++) {
  5579. result.m[index] = array[index + offset];
  5580. }
  5581. result._markAsUpdated();
  5582. };
  5583. /**
  5584. * Stores an array into a matrix after having multiplied each component by a given factor
  5585. * @param array defines the source array
  5586. * @param offset defines the offset in the source array
  5587. * @param scale defines the scaling factor
  5588. * @param result defines the target matrix
  5589. */
  5590. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5591. for (var index = 0; index < 16; index++) {
  5592. result.m[index] = array[index + offset] * scale;
  5593. }
  5594. result._markAsUpdated();
  5595. };
  5596. /**
  5597. * Stores a list of values (16) inside a given matrix
  5598. * @param initialM11 defines 1st value of 1st row
  5599. * @param initialM12 defines 2nd value of 1st row
  5600. * @param initialM13 defines 3rd value of 1st row
  5601. * @param initialM14 defines 4th value of 1st row
  5602. * @param initialM21 defines 1st value of 2nd row
  5603. * @param initialM22 defines 2nd value of 2nd row
  5604. * @param initialM23 defines 3rd value of 2nd row
  5605. * @param initialM24 defines 4th value of 2nd row
  5606. * @param initialM31 defines 1st value of 3rd row
  5607. * @param initialM32 defines 2nd value of 3rd row
  5608. * @param initialM33 defines 3rd value of 3rd row
  5609. * @param initialM34 defines 4th value of 3rd row
  5610. * @param initialM41 defines 1st value of 4th row
  5611. * @param initialM42 defines 2nd value of 4th row
  5612. * @param initialM43 defines 3rd value of 4th row
  5613. * @param initialM44 defines 4th value of 4th row
  5614. * @param result defines the target matrix
  5615. */
  5616. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5617. result.m[0] = initialM11;
  5618. result.m[1] = initialM12;
  5619. result.m[2] = initialM13;
  5620. result.m[3] = initialM14;
  5621. result.m[4] = initialM21;
  5622. result.m[5] = initialM22;
  5623. result.m[6] = initialM23;
  5624. result.m[7] = initialM24;
  5625. result.m[8] = initialM31;
  5626. result.m[9] = initialM32;
  5627. result.m[10] = initialM33;
  5628. result.m[11] = initialM34;
  5629. result.m[12] = initialM41;
  5630. result.m[13] = initialM42;
  5631. result.m[14] = initialM43;
  5632. result.m[15] = initialM44;
  5633. result._markAsUpdated();
  5634. };
  5635. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5636. /**
  5637. * Gets an identity matrix that must not be updated
  5638. */
  5639. get: function () {
  5640. return Matrix._identityReadOnly;
  5641. },
  5642. enumerable: true,
  5643. configurable: true
  5644. });
  5645. /**
  5646. * Creates new matrix from a list of values (16)
  5647. * @param initialM11 defines 1st value of 1st row
  5648. * @param initialM12 defines 2nd value of 1st row
  5649. * @param initialM13 defines 3rd value of 1st row
  5650. * @param initialM14 defines 4th value of 1st row
  5651. * @param initialM21 defines 1st value of 2nd row
  5652. * @param initialM22 defines 2nd value of 2nd row
  5653. * @param initialM23 defines 3rd value of 2nd row
  5654. * @param initialM24 defines 4th value of 2nd row
  5655. * @param initialM31 defines 1st value of 3rd row
  5656. * @param initialM32 defines 2nd value of 3rd row
  5657. * @param initialM33 defines 3rd value of 3rd row
  5658. * @param initialM34 defines 4th value of 3rd row
  5659. * @param initialM41 defines 1st value of 4th row
  5660. * @param initialM42 defines 2nd value of 4th row
  5661. * @param initialM43 defines 3rd value of 4th row
  5662. * @param initialM44 defines 4th value of 4th row
  5663. * @returns the new matrix
  5664. */
  5665. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5666. var result = new Matrix();
  5667. result.m[0] = initialM11;
  5668. result.m[1] = initialM12;
  5669. result.m[2] = initialM13;
  5670. result.m[3] = initialM14;
  5671. result.m[4] = initialM21;
  5672. result.m[5] = initialM22;
  5673. result.m[6] = initialM23;
  5674. result.m[7] = initialM24;
  5675. result.m[8] = initialM31;
  5676. result.m[9] = initialM32;
  5677. result.m[10] = initialM33;
  5678. result.m[11] = initialM34;
  5679. result.m[12] = initialM41;
  5680. result.m[13] = initialM42;
  5681. result.m[14] = initialM43;
  5682. result.m[15] = initialM44;
  5683. return result;
  5684. };
  5685. /**
  5686. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5687. * @param scale defines the scale vector3
  5688. * @param rotation defines the rotation quaternion
  5689. * @param translation defines the translation vector3
  5690. * @returns a new matrix
  5691. */
  5692. Matrix.Compose = function (scale, rotation, translation) {
  5693. var result = Matrix.Identity();
  5694. Matrix.ComposeToRef(scale, rotation, translation, result);
  5695. return result;
  5696. };
  5697. /**
  5698. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5699. * @param scale defines the scale vector3
  5700. * @param rotation defines the rotation quaternion
  5701. * @param translation defines the translation vector3
  5702. * @param result defines the target matrix
  5703. */
  5704. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5705. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5706. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5707. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5708. result.setTranslation(translation);
  5709. };
  5710. /**
  5711. * Creates a new identity matrix
  5712. * @returns a new identity matrix
  5713. */
  5714. Matrix.Identity = function () {
  5715. 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);
  5716. };
  5717. /**
  5718. * Creates a new identity matrix and stores the result in a given matrix
  5719. * @param result defines the target matrix
  5720. */
  5721. Matrix.IdentityToRef = function (result) {
  5722. 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);
  5723. };
  5724. /**
  5725. * Creates a new zero matrix
  5726. * @returns a new zero matrix
  5727. */
  5728. Matrix.Zero = function () {
  5729. 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);
  5730. };
  5731. /**
  5732. * Creates a new rotation matrix for "angle" radians around the X axis
  5733. * @param angle defines the angle (in radians) to use
  5734. * @return the new matrix
  5735. */
  5736. Matrix.RotationX = function (angle) {
  5737. var result = new Matrix();
  5738. Matrix.RotationXToRef(angle, result);
  5739. return result;
  5740. };
  5741. /**
  5742. * Creates a new matrix as the invert of a given matrix
  5743. * @param source defines the source matrix
  5744. * @returns the new matrix
  5745. */
  5746. Matrix.Invert = function (source) {
  5747. var result = new Matrix();
  5748. source.invertToRef(result);
  5749. return result;
  5750. };
  5751. /**
  5752. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5753. * @param angle defines the angle (in radians) to use
  5754. * @param result defines the target matrix
  5755. */
  5756. Matrix.RotationXToRef = function (angle, result) {
  5757. var s = Math.sin(angle);
  5758. var c = Math.cos(angle);
  5759. result.m[0] = 1.0;
  5760. result.m[15] = 1.0;
  5761. result.m[5] = c;
  5762. result.m[10] = c;
  5763. result.m[9] = -s;
  5764. result.m[6] = s;
  5765. result.m[1] = 0.0;
  5766. result.m[2] = 0.0;
  5767. result.m[3] = 0.0;
  5768. result.m[4] = 0.0;
  5769. result.m[7] = 0.0;
  5770. result.m[8] = 0.0;
  5771. result.m[11] = 0.0;
  5772. result.m[12] = 0.0;
  5773. result.m[13] = 0.0;
  5774. result.m[14] = 0.0;
  5775. result._markAsUpdated();
  5776. };
  5777. /**
  5778. * Creates a new rotation matrix for "angle" radians around the Y axis
  5779. * @param angle defines the angle (in radians) to use
  5780. * @return the new matrix
  5781. */
  5782. Matrix.RotationY = function (angle) {
  5783. var result = new Matrix();
  5784. Matrix.RotationYToRef(angle, result);
  5785. return result;
  5786. };
  5787. /**
  5788. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5789. * @param angle defines the angle (in radians) to use
  5790. * @param result defines the target matrix
  5791. */
  5792. Matrix.RotationYToRef = function (angle, result) {
  5793. var s = Math.sin(angle);
  5794. var c = Math.cos(angle);
  5795. result.m[5] = 1.0;
  5796. result.m[15] = 1.0;
  5797. result.m[0] = c;
  5798. result.m[2] = -s;
  5799. result.m[8] = s;
  5800. result.m[10] = c;
  5801. result.m[1] = 0.0;
  5802. result.m[3] = 0.0;
  5803. result.m[4] = 0.0;
  5804. result.m[6] = 0.0;
  5805. result.m[7] = 0.0;
  5806. result.m[9] = 0.0;
  5807. result.m[11] = 0.0;
  5808. result.m[12] = 0.0;
  5809. result.m[13] = 0.0;
  5810. result.m[14] = 0.0;
  5811. result._markAsUpdated();
  5812. };
  5813. /**
  5814. * Creates a new rotation matrix for "angle" radians around the Z axis
  5815. * @param angle defines the angle (in radians) to use
  5816. * @return the new matrix
  5817. */
  5818. Matrix.RotationZ = function (angle) {
  5819. var result = new Matrix();
  5820. Matrix.RotationZToRef(angle, result);
  5821. return result;
  5822. };
  5823. /**
  5824. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5825. * @param angle defines the angle (in radians) to use
  5826. * @param result defines the target matrix
  5827. */
  5828. Matrix.RotationZToRef = function (angle, result) {
  5829. var s = Math.sin(angle);
  5830. var c = Math.cos(angle);
  5831. result.m[10] = 1.0;
  5832. result.m[15] = 1.0;
  5833. result.m[0] = c;
  5834. result.m[1] = s;
  5835. result.m[4] = -s;
  5836. result.m[5] = c;
  5837. result.m[2] = 0.0;
  5838. result.m[3] = 0.0;
  5839. result.m[6] = 0.0;
  5840. result.m[7] = 0.0;
  5841. result.m[8] = 0.0;
  5842. result.m[9] = 0.0;
  5843. result.m[11] = 0.0;
  5844. result.m[12] = 0.0;
  5845. result.m[13] = 0.0;
  5846. result.m[14] = 0.0;
  5847. result._markAsUpdated();
  5848. };
  5849. /**
  5850. * Creates a new rotation matrix for "angle" radians around the given axis
  5851. * @param axis defines the axis to use
  5852. * @param angle defines the angle (in radians) to use
  5853. * @return the new matrix
  5854. */
  5855. Matrix.RotationAxis = function (axis, angle) {
  5856. var result = Matrix.Zero();
  5857. Matrix.RotationAxisToRef(axis, angle, result);
  5858. return result;
  5859. };
  5860. /**
  5861. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  5862. * @param axis defines the axis to use
  5863. * @param angle defines the angle (in radians) to use
  5864. * @param result defines the target matrix
  5865. */
  5866. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5867. var s = Math.sin(-angle);
  5868. var c = Math.cos(-angle);
  5869. var c1 = 1 - c;
  5870. axis.normalize();
  5871. result.m[0] = (axis.x * axis.x) * c1 + c;
  5872. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5873. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5874. result.m[3] = 0.0;
  5875. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  5876. result.m[5] = (axis.y * axis.y) * c1 + c;
  5877. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  5878. result.m[7] = 0.0;
  5879. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  5880. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  5881. result.m[10] = (axis.z * axis.z) * c1 + c;
  5882. result.m[11] = 0.0;
  5883. result.m[15] = 1.0;
  5884. result._markAsUpdated();
  5885. };
  5886. /**
  5887. * Creates a rotation matrix
  5888. * @param yaw defines the yaw angle in radians (Y axis)
  5889. * @param pitch defines the pitch angle in radians (X axis)
  5890. * @param roll defines the roll angle in radians (X axis)
  5891. * @returns the new rotation matrix
  5892. */
  5893. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5894. var result = new Matrix();
  5895. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  5896. return result;
  5897. };
  5898. /**
  5899. * Creates a rotation matrix and stores it in a given matrix
  5900. * @param yaw defines the yaw angle in radians (Y axis)
  5901. * @param pitch defines the pitch angle in radians (X axis)
  5902. * @param roll defines the roll angle in radians (X axis)
  5903. * @param result defines the target matrix
  5904. */
  5905. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5906. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  5907. this._tempQuaternion.toRotationMatrix(result);
  5908. };
  5909. /**
  5910. * Creates a scaling matrix
  5911. * @param x defines the scale factor on X axis
  5912. * @param y defines the scale factor on Y axis
  5913. * @param z defines the scale factor on Z axis
  5914. * @returns the new matrix
  5915. */
  5916. Matrix.Scaling = function (x, y, z) {
  5917. var result = Matrix.Zero();
  5918. Matrix.ScalingToRef(x, y, z, result);
  5919. return result;
  5920. };
  5921. /**
  5922. * Creates a scaling matrix and stores it in a given matrix
  5923. * @param x defines the scale factor on X axis
  5924. * @param y defines the scale factor on Y axis
  5925. * @param z defines the scale factor on Z axis
  5926. * @param result defines the target matrix
  5927. */
  5928. Matrix.ScalingToRef = function (x, y, z, result) {
  5929. result.m[0] = x;
  5930. result.m[1] = 0.0;
  5931. result.m[2] = 0.0;
  5932. result.m[3] = 0.0;
  5933. result.m[4] = 0.0;
  5934. result.m[5] = y;
  5935. result.m[6] = 0.0;
  5936. result.m[7] = 0.0;
  5937. result.m[8] = 0.0;
  5938. result.m[9] = 0.0;
  5939. result.m[10] = z;
  5940. result.m[11] = 0.0;
  5941. result.m[12] = 0.0;
  5942. result.m[13] = 0.0;
  5943. result.m[14] = 0.0;
  5944. result.m[15] = 1.0;
  5945. result._markAsUpdated();
  5946. };
  5947. /**
  5948. * Creates a translation matrix
  5949. * @param x defines the translation on X axis
  5950. * @param y defines the translation on Y axis
  5951. * @param z defines the translationon Z axis
  5952. * @returns the new matrix
  5953. */
  5954. Matrix.Translation = function (x, y, z) {
  5955. var result = Matrix.Identity();
  5956. Matrix.TranslationToRef(x, y, z, result);
  5957. return result;
  5958. };
  5959. /**
  5960. * Creates a translation matrix and stores it in a given matrix
  5961. * @param x defines the translation on X axis
  5962. * @param y defines the translation on Y axis
  5963. * @param z defines the translationon Z axis
  5964. * @param result defines the target matrix
  5965. */
  5966. Matrix.TranslationToRef = function (x, y, z, result) {
  5967. 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);
  5968. };
  5969. /**
  5970. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5971. * @param startValue defines the start value
  5972. * @param endValue defines the end value
  5973. * @param gradient defines the gradient factor
  5974. * @returns the new matrix
  5975. */
  5976. Matrix.Lerp = function (startValue, endValue, gradient) {
  5977. var result = Matrix.Zero();
  5978. Matrix.LerpToRef(startValue, endValue, gradient, result);
  5979. return result;
  5980. };
  5981. /**
  5982. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  5983. * @param startValue defines the start value
  5984. * @param endValue defines the end value
  5985. * @param gradient defines the gradient factor
  5986. * @param result defines the Matrix object where to store data
  5987. */
  5988. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  5989. for (var index = 0; index < 16; index++) {
  5990. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  5991. }
  5992. result._markAsUpdated();
  5993. };
  5994. /**
  5995. * Builds a new matrix whose values are computed by:
  5996. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  5997. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  5998. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  5999. * @param startValue defines the first matrix
  6000. * @param endValue defines the second matrix
  6001. * @param gradient defines the gradient between the two matrices
  6002. * @returns the new matrix
  6003. */
  6004. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6005. var result = Matrix.Zero();
  6006. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6007. return result;
  6008. };
  6009. /**
  6010. * Update a matrix to values which are computed by:
  6011. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6012. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6013. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6014. * @param startValue defines the first matrix
  6015. * @param endValue defines the second matrix
  6016. * @param gradient defines the gradient between the two matrices
  6017. * @param result defines the target matrix
  6018. */
  6019. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6020. var startScale = MathTmp.Vector3[0];
  6021. var startRotation = MathTmp.Quaternion[0];
  6022. var startTranslation = MathTmp.Vector3[1];
  6023. startValue.decompose(startScale, startRotation, startTranslation);
  6024. var endScale = MathTmp.Vector3[2];
  6025. var endRotation = MathTmp.Quaternion[1];
  6026. var endTranslation = MathTmp.Vector3[3];
  6027. endValue.decompose(endScale, endRotation, endTranslation);
  6028. var resultScale = MathTmp.Vector3[4];
  6029. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6030. var resultRotation = MathTmp.Quaternion[2];
  6031. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6032. var resultTranslation = MathTmp.Vector3[5];
  6033. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6034. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6035. };
  6036. /**
  6037. * 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"
  6038. * This function works in left handed mode
  6039. * @param eye defines the final position of the entity
  6040. * @param target defines where the entity should look at
  6041. * @param up defines the up vector for the entity
  6042. * @returns the new matrix
  6043. */
  6044. Matrix.LookAtLH = function (eye, target, up) {
  6045. var result = Matrix.Zero();
  6046. Matrix.LookAtLHToRef(eye, target, up, result);
  6047. return result;
  6048. };
  6049. /**
  6050. * 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".
  6051. * This function works in left handed mode
  6052. * @param eye defines the final position of the entity
  6053. * @param target defines where the entity should look at
  6054. * @param up defines the up vector for the entity
  6055. * @param result defines the target matrix
  6056. */
  6057. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6058. // Z axis
  6059. target.subtractToRef(eye, this._zAxis);
  6060. this._zAxis.normalize();
  6061. // X axis
  6062. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6063. if (this._xAxis.lengthSquared() === 0) {
  6064. this._xAxis.x = 1.0;
  6065. }
  6066. else {
  6067. this._xAxis.normalize();
  6068. }
  6069. // Y axis
  6070. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6071. this._yAxis.normalize();
  6072. // Eye angles
  6073. var ex = -Vector3.Dot(this._xAxis, eye);
  6074. var ey = -Vector3.Dot(this._yAxis, eye);
  6075. var ez = -Vector3.Dot(this._zAxis, eye);
  6076. 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);
  6077. };
  6078. /**
  6079. * 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"
  6080. * This function works in right handed mode
  6081. * @param eye defines the final position of the entity
  6082. * @param target defines where the entity should look at
  6083. * @param up defines the up vector for the entity
  6084. * @returns the new matrix
  6085. */
  6086. Matrix.LookAtRH = function (eye, target, up) {
  6087. var result = Matrix.Zero();
  6088. Matrix.LookAtRHToRef(eye, target, up, result);
  6089. return result;
  6090. };
  6091. /**
  6092. * 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".
  6093. * This function works in right handed mode
  6094. * @param eye defines the final position of the entity
  6095. * @param target defines where the entity should look at
  6096. * @param up defines the up vector for the entity
  6097. * @param result defines the target matrix
  6098. */
  6099. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6100. // Z axis
  6101. eye.subtractToRef(target, this._zAxis);
  6102. this._zAxis.normalize();
  6103. // X axis
  6104. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6105. if (this._xAxis.lengthSquared() === 0) {
  6106. this._xAxis.x = 1.0;
  6107. }
  6108. else {
  6109. this._xAxis.normalize();
  6110. }
  6111. // Y axis
  6112. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6113. this._yAxis.normalize();
  6114. // Eye angles
  6115. var ex = -Vector3.Dot(this._xAxis, eye);
  6116. var ey = -Vector3.Dot(this._yAxis, eye);
  6117. var ez = -Vector3.Dot(this._zAxis, eye);
  6118. 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);
  6119. };
  6120. /**
  6121. * Create a left-handed orthographic projection matrix
  6122. * @param width defines the viewport width
  6123. * @param height defines the viewport height
  6124. * @param znear defines the near clip plane
  6125. * @param zfar defines the far clip plane
  6126. * @returns a new matrix as a left-handed orthographic projection matrix
  6127. */
  6128. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6129. var matrix = Matrix.Zero();
  6130. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6131. return matrix;
  6132. };
  6133. /**
  6134. * Store a left-handed orthographic projection to a given matrix
  6135. * @param width defines the viewport width
  6136. * @param height defines the viewport height
  6137. * @param znear defines the near clip plane
  6138. * @param zfar defines the far clip plane
  6139. * @param result defines the target matrix
  6140. */
  6141. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6142. var n = znear;
  6143. var f = zfar;
  6144. var a = 2.0 / width;
  6145. var b = 2.0 / height;
  6146. var c = 2.0 / (f - n);
  6147. var d = -(f + n) / (f - n);
  6148. 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);
  6149. };
  6150. /**
  6151. * Create a left-handed orthographic projection matrix
  6152. * @param left defines the viewport left coordinate
  6153. * @param right defines the viewport right coordinate
  6154. * @param bottom defines the viewport bottom coordinate
  6155. * @param top defines the viewport top coordinate
  6156. * @param znear defines the near clip plane
  6157. * @param zfar defines the far clip plane
  6158. * @returns a new matrix as a left-handed orthographic projection matrix
  6159. */
  6160. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6161. var matrix = Matrix.Zero();
  6162. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6163. return matrix;
  6164. };
  6165. /**
  6166. * Stores a left-handed orthographic projection into a given matrix
  6167. * @param left defines the viewport left coordinate
  6168. * @param right defines the viewport right coordinate
  6169. * @param bottom defines the viewport bottom coordinate
  6170. * @param top defines the viewport top coordinate
  6171. * @param znear defines the near clip plane
  6172. * @param zfar defines the far clip plane
  6173. * @param result defines the target matrix
  6174. */
  6175. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6176. var n = znear;
  6177. var f = zfar;
  6178. var a = 2.0 / (right - left);
  6179. var b = 2.0 / (top - bottom);
  6180. var c = 2.0 / (f - n);
  6181. var d = -(f + n) / (f - n);
  6182. var i0 = (left + right) / (left - right);
  6183. var i1 = (top + bottom) / (bottom - top);
  6184. 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);
  6185. };
  6186. /**
  6187. * Creates a right-handed orthographic projection matrix
  6188. * @param left defines the viewport left coordinate
  6189. * @param right defines the viewport right coordinate
  6190. * @param bottom defines the viewport bottom coordinate
  6191. * @param top defines the viewport top coordinate
  6192. * @param znear defines the near clip plane
  6193. * @param zfar defines the far clip plane
  6194. * @returns a new matrix as a right-handed orthographic projection matrix
  6195. */
  6196. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6197. var matrix = Matrix.Zero();
  6198. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6199. return matrix;
  6200. };
  6201. /**
  6202. * Stores a right-handed orthographic projection into a given matrix
  6203. * @param left defines the viewport left coordinate
  6204. * @param right defines the viewport right coordinate
  6205. * @param bottom defines the viewport bottom coordinate
  6206. * @param top defines the viewport top coordinate
  6207. * @param znear defines the near clip plane
  6208. * @param zfar defines the far clip plane
  6209. * @param result defines the target matrix
  6210. */
  6211. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6212. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6213. result.m[10] *= -1.0;
  6214. };
  6215. /**
  6216. * Creates a left-handed perspective projection matrix
  6217. * @param width defines the viewport width
  6218. * @param height defines the viewport height
  6219. * @param znear defines the near clip plane
  6220. * @param zfar defines the far clip plane
  6221. * @returns a new matrix as a left-handed perspective projection matrix
  6222. */
  6223. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6224. var matrix = Matrix.Zero();
  6225. var n = znear;
  6226. var f = zfar;
  6227. var a = 2.0 * n / width;
  6228. var b = 2.0 * n / height;
  6229. var c = (f + n) / (f - n);
  6230. var d = -2.0 * f * n / (f - n);
  6231. 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);
  6232. return matrix;
  6233. };
  6234. /**
  6235. * Creates a left-handed perspective projection matrix
  6236. * @param fov defines the horizontal field of view
  6237. * @param aspect defines the aspect ratio
  6238. * @param znear defines the near clip plane
  6239. * @param zfar defines the far clip plane
  6240. * @returns a new matrix as a left-handed perspective projection matrix
  6241. */
  6242. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6243. var matrix = Matrix.Zero();
  6244. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6245. return matrix;
  6246. };
  6247. /**
  6248. * Stores a left-handed perspective projection into a given matrix
  6249. * @param fov defines the horizontal field of view
  6250. * @param aspect defines the aspect ratio
  6251. * @param znear defines the near clip plane
  6252. * @param zfar defines the far clip plane
  6253. * @param result defines the target matrix
  6254. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6255. */
  6256. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6257. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6258. var n = znear;
  6259. var f = zfar;
  6260. var t = 1.0 / (Math.tan(fov * 0.5));
  6261. var a = isVerticalFovFixed ? (t / aspect) : t;
  6262. var b = isVerticalFovFixed ? t : (t * aspect);
  6263. var c = (f + n) / (f - n);
  6264. var d = -2.0 * f * n / (f - n);
  6265. 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);
  6266. };
  6267. /**
  6268. * Creates a right-handed perspective projection matrix
  6269. * @param fov defines the horizontal field of view
  6270. * @param aspect defines the aspect ratio
  6271. * @param znear defines the near clip plane
  6272. * @param zfar defines the far clip plane
  6273. * @returns a new matrix as a right-handed perspective projection matrix
  6274. */
  6275. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6276. var matrix = Matrix.Zero();
  6277. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6278. return matrix;
  6279. };
  6280. /**
  6281. * Stores a right-handed perspective projection into a given matrix
  6282. * @param fov defines the horizontal field of view
  6283. * @param aspect defines the aspect ratio
  6284. * @param znear defines the near clip plane
  6285. * @param zfar defines the far clip plane
  6286. * @param result defines the target matrix
  6287. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6288. */
  6289. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6290. //alternatively this could be expressed as:
  6291. // m = PerspectiveFovLHToRef
  6292. // m[10] *= -1.0;
  6293. // m[11] *= -1.0;
  6294. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6295. var n = znear;
  6296. var f = zfar;
  6297. var t = 1.0 / (Math.tan(fov * 0.5));
  6298. var a = isVerticalFovFixed ? (t / aspect) : t;
  6299. var b = isVerticalFovFixed ? t : (t * aspect);
  6300. var c = -(f + n) / (f - n);
  6301. var d = -2 * f * n / (f - n);
  6302. 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);
  6303. };
  6304. /**
  6305. * Stores a perspective projection for WebVR info a given matrix
  6306. * @param fov defines the field of view
  6307. * @param znear defines the near clip plane
  6308. * @param zfar defines the far clip plane
  6309. * @param result defines the target matrix
  6310. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6311. */
  6312. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6313. if (rightHanded === void 0) { rightHanded = false; }
  6314. var rightHandedFactor = rightHanded ? -1 : 1;
  6315. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6316. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6317. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6318. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6319. var xScale = 2.0 / (leftTan + rightTan);
  6320. var yScale = 2.0 / (upTan + downTan);
  6321. result.m[0] = xScale;
  6322. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6323. result.m[5] = yScale;
  6324. result.m[6] = result.m[7] = 0.0;
  6325. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6326. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6327. result.m[10] = -zfar / (znear - zfar);
  6328. result.m[11] = 1.0 * rightHandedFactor;
  6329. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6330. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6331. result._markAsUpdated();
  6332. };
  6333. /**
  6334. * Computes a complete transformation matrix
  6335. * @param viewport defines the viewport to use
  6336. * @param world defines the world matrix
  6337. * @param view defines the view matrix
  6338. * @param projection defines the projection matrix
  6339. * @param zmin defines the near clip plane
  6340. * @param zmax defines the far clip plane
  6341. * @returns the transformation matrix
  6342. */
  6343. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6344. var cw = viewport.width;
  6345. var ch = viewport.height;
  6346. var cx = viewport.x;
  6347. var cy = viewport.y;
  6348. 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);
  6349. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6350. };
  6351. /**
  6352. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6353. * @param matrix defines the matrix to use
  6354. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6355. */
  6356. Matrix.GetAsMatrix2x2 = function (matrix) {
  6357. return new Float32Array([
  6358. matrix.m[0], matrix.m[1],
  6359. matrix.m[4], matrix.m[5]
  6360. ]);
  6361. };
  6362. /**
  6363. * Extracts a 3x3 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 9 elements : the 3x3 matrix extracted from the given matrix
  6366. */
  6367. Matrix.GetAsMatrix3x3 = function (matrix) {
  6368. return new Float32Array([
  6369. matrix.m[0], matrix.m[1], matrix.m[2],
  6370. matrix.m[4], matrix.m[5], matrix.m[6],
  6371. matrix.m[8], matrix.m[9], matrix.m[10]
  6372. ]);
  6373. };
  6374. /**
  6375. * Compute the transpose of a given matrix
  6376. * @param matrix defines the matrix to transpose
  6377. * @returns the new matrix
  6378. */
  6379. Matrix.Transpose = function (matrix) {
  6380. var result = new Matrix();
  6381. Matrix.TransposeToRef(matrix, result);
  6382. return result;
  6383. };
  6384. /**
  6385. * Compute the transpose of a matrix and store it in a target matrix
  6386. * @param matrix defines the matrix to transpose
  6387. * @param result defines the target matrix
  6388. */
  6389. Matrix.TransposeToRef = function (matrix, result) {
  6390. result.m[0] = matrix.m[0];
  6391. result.m[1] = matrix.m[4];
  6392. result.m[2] = matrix.m[8];
  6393. result.m[3] = matrix.m[12];
  6394. result.m[4] = matrix.m[1];
  6395. result.m[5] = matrix.m[5];
  6396. result.m[6] = matrix.m[9];
  6397. result.m[7] = matrix.m[13];
  6398. result.m[8] = matrix.m[2];
  6399. result.m[9] = matrix.m[6];
  6400. result.m[10] = matrix.m[10];
  6401. result.m[11] = matrix.m[14];
  6402. result.m[12] = matrix.m[3];
  6403. result.m[13] = matrix.m[7];
  6404. result.m[14] = matrix.m[11];
  6405. result.m[15] = matrix.m[15];
  6406. };
  6407. /**
  6408. * Computes a reflection matrix from a plane
  6409. * @param plane defines the reflection plane
  6410. * @returns a new matrix
  6411. */
  6412. Matrix.Reflection = function (plane) {
  6413. var matrix = new Matrix();
  6414. Matrix.ReflectionToRef(plane, matrix);
  6415. return matrix;
  6416. };
  6417. /**
  6418. * Computes a reflection matrix from a plane
  6419. * @param plane defines the reflection plane
  6420. * @param result defines the target matrix
  6421. */
  6422. Matrix.ReflectionToRef = function (plane, result) {
  6423. plane.normalize();
  6424. var x = plane.normal.x;
  6425. var y = plane.normal.y;
  6426. var z = plane.normal.z;
  6427. var temp = -2 * x;
  6428. var temp2 = -2 * y;
  6429. var temp3 = -2 * z;
  6430. result.m[0] = (temp * x) + 1;
  6431. result.m[1] = temp2 * x;
  6432. result.m[2] = temp3 * x;
  6433. result.m[3] = 0.0;
  6434. result.m[4] = temp * y;
  6435. result.m[5] = (temp2 * y) + 1;
  6436. result.m[6] = temp3 * y;
  6437. result.m[7] = 0.0;
  6438. result.m[8] = temp * z;
  6439. result.m[9] = temp2 * z;
  6440. result.m[10] = (temp3 * z) + 1;
  6441. result.m[11] = 0.0;
  6442. result.m[12] = temp * plane.d;
  6443. result.m[13] = temp2 * plane.d;
  6444. result.m[14] = temp3 * plane.d;
  6445. result.m[15] = 1.0;
  6446. result._markAsUpdated();
  6447. };
  6448. /**
  6449. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6450. * @param xaxis defines the value of the 1st axis
  6451. * @param yaxis defines the value of the 2nd axis
  6452. * @param zaxis defines the value of the 3rd axis
  6453. * @param result defines the target matrix
  6454. */
  6455. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6456. result.m[0] = xaxis.x;
  6457. result.m[1] = xaxis.y;
  6458. result.m[2] = xaxis.z;
  6459. result.m[3] = 0.0;
  6460. result.m[4] = yaxis.x;
  6461. result.m[5] = yaxis.y;
  6462. result.m[6] = yaxis.z;
  6463. result.m[7] = 0.0;
  6464. result.m[8] = zaxis.x;
  6465. result.m[9] = zaxis.y;
  6466. result.m[10] = zaxis.z;
  6467. result.m[11] = 0.0;
  6468. result.m[12] = 0.0;
  6469. result.m[13] = 0.0;
  6470. result.m[14] = 0.0;
  6471. result.m[15] = 1.0;
  6472. result._markAsUpdated();
  6473. };
  6474. /**
  6475. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6476. * @param quat defines the quaternion to use
  6477. * @param result defines the target matrix
  6478. */
  6479. Matrix.FromQuaternionToRef = function (quat, result) {
  6480. var xx = quat.x * quat.x;
  6481. var yy = quat.y * quat.y;
  6482. var zz = quat.z * quat.z;
  6483. var xy = quat.x * quat.y;
  6484. var zw = quat.z * quat.w;
  6485. var zx = quat.z * quat.x;
  6486. var yw = quat.y * quat.w;
  6487. var yz = quat.y * quat.z;
  6488. var xw = quat.x * quat.w;
  6489. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6490. result.m[1] = 2.0 * (xy + zw);
  6491. result.m[2] = 2.0 * (zx - yw);
  6492. result.m[3] = 0.0;
  6493. result.m[4] = 2.0 * (xy - zw);
  6494. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6495. result.m[6] = 2.0 * (yz + xw);
  6496. result.m[7] = 0.0;
  6497. result.m[8] = 2.0 * (zx + yw);
  6498. result.m[9] = 2.0 * (yz - xw);
  6499. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6500. result.m[11] = 0.0;
  6501. result.m[12] = 0.0;
  6502. result.m[13] = 0.0;
  6503. result.m[14] = 0.0;
  6504. result.m[15] = 1.0;
  6505. result._markAsUpdated();
  6506. };
  6507. Matrix._tempQuaternion = new Quaternion();
  6508. Matrix._xAxis = Vector3.Zero();
  6509. Matrix._yAxis = Vector3.Zero();
  6510. Matrix._zAxis = Vector3.Zero();
  6511. Matrix._updateFlagSeed = 0;
  6512. Matrix._identityReadOnly = Matrix.Identity();
  6513. return Matrix;
  6514. }());
  6515. BABYLON.Matrix = Matrix;
  6516. var Plane = /** @class */ (function () {
  6517. /**
  6518. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6519. */
  6520. function Plane(a, b, c, d) {
  6521. this.normal = new Vector3(a, b, c);
  6522. this.d = d;
  6523. }
  6524. /**
  6525. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6526. */
  6527. Plane.prototype.asArray = function () {
  6528. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6529. };
  6530. // Methods
  6531. /**
  6532. * Returns a new plane copied from the current Plane.
  6533. */
  6534. Plane.prototype.clone = function () {
  6535. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6536. };
  6537. /**
  6538. * Returns the string "Plane".
  6539. */
  6540. Plane.prototype.getClassName = function () {
  6541. return "Plane";
  6542. };
  6543. /**
  6544. * Returns the Plane hash code.
  6545. */
  6546. Plane.prototype.getHashCode = function () {
  6547. var hash = this.normal.getHashCode();
  6548. hash = (hash * 397) ^ (this.d || 0);
  6549. return hash;
  6550. };
  6551. /**
  6552. * Normalize the current Plane in place.
  6553. * Returns the updated Plane.
  6554. */
  6555. Plane.prototype.normalize = function () {
  6556. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6557. var magnitude = 0.0;
  6558. if (norm !== 0) {
  6559. magnitude = 1.0 / norm;
  6560. }
  6561. this.normal.x *= magnitude;
  6562. this.normal.y *= magnitude;
  6563. this.normal.z *= magnitude;
  6564. this.d *= magnitude;
  6565. return this;
  6566. };
  6567. /**
  6568. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6569. */
  6570. Plane.prototype.transform = function (transformation) {
  6571. var transposedMatrix = Matrix.Transpose(transformation);
  6572. var x = this.normal.x;
  6573. var y = this.normal.y;
  6574. var z = this.normal.z;
  6575. var d = this.d;
  6576. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6577. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6578. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6579. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6580. return new Plane(normalX, normalY, normalZ, finalD);
  6581. };
  6582. /**
  6583. * Returns the dot product (float) of the point coordinates and the plane normal.
  6584. */
  6585. Plane.prototype.dotCoordinate = function (point) {
  6586. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6587. };
  6588. /**
  6589. * Updates the current Plane from the plane defined by the three given points.
  6590. * Returns the updated Plane.
  6591. */
  6592. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6593. var x1 = point2.x - point1.x;
  6594. var y1 = point2.y - point1.y;
  6595. var z1 = point2.z - point1.z;
  6596. var x2 = point3.x - point1.x;
  6597. var y2 = point3.y - point1.y;
  6598. var z2 = point3.z - point1.z;
  6599. var yz = (y1 * z2) - (z1 * y2);
  6600. var xz = (z1 * x2) - (x1 * z2);
  6601. var xy = (x1 * y2) - (y1 * x2);
  6602. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6603. var invPyth;
  6604. if (pyth !== 0) {
  6605. invPyth = 1.0 / pyth;
  6606. }
  6607. else {
  6608. invPyth = 0.0;
  6609. }
  6610. this.normal.x = yz * invPyth;
  6611. this.normal.y = xz * invPyth;
  6612. this.normal.z = xy * invPyth;
  6613. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6614. return this;
  6615. };
  6616. /**
  6617. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6618. */
  6619. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6620. var dot = Vector3.Dot(this.normal, direction);
  6621. return (dot <= epsilon);
  6622. };
  6623. /**
  6624. * Returns the signed distance (float) from the given point to the Plane.
  6625. */
  6626. Plane.prototype.signedDistanceTo = function (point) {
  6627. return Vector3.Dot(point, this.normal) + this.d;
  6628. };
  6629. // Statics
  6630. /**
  6631. * Returns a new Plane from the given array.
  6632. */
  6633. Plane.FromArray = function (array) {
  6634. return new Plane(array[0], array[1], array[2], array[3]);
  6635. };
  6636. /**
  6637. * Returns a new Plane defined by the three given points.
  6638. */
  6639. Plane.FromPoints = function (point1, point2, point3) {
  6640. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6641. result.copyFromPoints(point1, point2, point3);
  6642. return result;
  6643. };
  6644. /**
  6645. * Returns a new Plane the normal vector to this plane at the given origin point.
  6646. * Note : the vector "normal" is updated because normalized.
  6647. */
  6648. Plane.FromPositionAndNormal = function (origin, normal) {
  6649. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6650. normal.normalize();
  6651. result.normal = normal;
  6652. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6653. return result;
  6654. };
  6655. /**
  6656. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6657. */
  6658. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6659. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6660. return Vector3.Dot(point, normal) + d;
  6661. };
  6662. return Plane;
  6663. }());
  6664. BABYLON.Plane = Plane;
  6665. var Viewport = /** @class */ (function () {
  6666. /**
  6667. * Creates a Viewport object located at (x, y) and sized (width, height).
  6668. */
  6669. function Viewport(x, y, width, height) {
  6670. this.x = x;
  6671. this.y = y;
  6672. this.width = width;
  6673. this.height = height;
  6674. }
  6675. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6676. if (renderWidthOrEngine.getRenderWidth) {
  6677. var engine = renderWidthOrEngine;
  6678. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6679. }
  6680. var renderWidth = renderWidthOrEngine;
  6681. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6682. };
  6683. /**
  6684. * Returns a new Viewport copied from the current one.
  6685. */
  6686. Viewport.prototype.clone = function () {
  6687. return new Viewport(this.x, this.y, this.width, this.height);
  6688. };
  6689. return Viewport;
  6690. }());
  6691. BABYLON.Viewport = Viewport;
  6692. var Frustum = /** @class */ (function () {
  6693. function Frustum() {
  6694. }
  6695. /**
  6696. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6697. */
  6698. Frustum.GetPlanes = function (transform) {
  6699. var frustumPlanes = [];
  6700. for (var index = 0; index < 6; index++) {
  6701. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6702. }
  6703. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6704. return frustumPlanes;
  6705. };
  6706. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6707. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6708. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6709. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6710. frustumPlane.d = transform.m[15] + transform.m[14];
  6711. frustumPlane.normalize();
  6712. };
  6713. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6714. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6715. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6716. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6717. frustumPlane.d = transform.m[15] - transform.m[14];
  6718. frustumPlane.normalize();
  6719. };
  6720. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6721. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6722. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6723. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6724. frustumPlane.d = transform.m[15] + transform.m[12];
  6725. frustumPlane.normalize();
  6726. };
  6727. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6728. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6729. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6730. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6731. frustumPlane.d = transform.m[15] - transform.m[12];
  6732. frustumPlane.normalize();
  6733. };
  6734. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6735. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6736. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6737. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6738. frustumPlane.d = transform.m[15] - transform.m[13];
  6739. frustumPlane.normalize();
  6740. };
  6741. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6742. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6743. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6744. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6745. frustumPlane.d = transform.m[15] + transform.m[13];
  6746. frustumPlane.normalize();
  6747. };
  6748. /**
  6749. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6750. */
  6751. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6752. // Near
  6753. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6754. // Far
  6755. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6756. // Left
  6757. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6758. // Right
  6759. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6760. // Top
  6761. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6762. // Bottom
  6763. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6764. };
  6765. return Frustum;
  6766. }());
  6767. BABYLON.Frustum = Frustum;
  6768. /** Defines supported spaces */
  6769. var Space;
  6770. (function (Space) {
  6771. /** Local (object) space */
  6772. Space[Space["LOCAL"] = 0] = "LOCAL";
  6773. /** World space */
  6774. Space[Space["WORLD"] = 1] = "WORLD";
  6775. /** Bone space */
  6776. Space[Space["BONE"] = 2] = "BONE";
  6777. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6778. /** Defines the 3 main axes */
  6779. var Axis = /** @class */ (function () {
  6780. function Axis() {
  6781. }
  6782. /** X axis */
  6783. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6784. /** Y axis */
  6785. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6786. /** Z axis */
  6787. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6788. return Axis;
  6789. }());
  6790. BABYLON.Axis = Axis;
  6791. ;
  6792. var BezierCurve = /** @class */ (function () {
  6793. function BezierCurve() {
  6794. }
  6795. /**
  6796. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats.
  6797. */
  6798. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6799. // Extract X (which is equal to time here)
  6800. var f0 = 1 - 3 * x2 + 3 * x1;
  6801. var f1 = 3 * x2 - 6 * x1;
  6802. var f2 = 3 * x1;
  6803. var refinedT = t;
  6804. for (var i = 0; i < 5; i++) {
  6805. var refinedT2 = refinedT * refinedT;
  6806. var refinedT3 = refinedT2 * refinedT;
  6807. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6808. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6809. refinedT -= (x - t) * slope;
  6810. refinedT = Math.min(1, Math.max(0, refinedT));
  6811. }
  6812. // Resolve cubic bezier for the given x
  6813. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6814. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6815. Math.pow(refinedT, 3);
  6816. };
  6817. return BezierCurve;
  6818. }());
  6819. BABYLON.BezierCurve = BezierCurve;
  6820. /**
  6821. * Defines potential orientation for back face culling
  6822. */
  6823. var Orientation;
  6824. (function (Orientation) {
  6825. /**
  6826. * Clockwise
  6827. */
  6828. Orientation[Orientation["CW"] = 0] = "CW";
  6829. /** Counter clockwise */
  6830. Orientation[Orientation["CCW"] = 1] = "CCW";
  6831. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6832. /**
  6833. * Defines angle representation
  6834. */
  6835. var Angle = /** @class */ (function () {
  6836. /**
  6837. * Creates an Angle object of "radians" radians (float).
  6838. */
  6839. function Angle(radians) {
  6840. this._radians = radians;
  6841. if (this._radians < 0.0)
  6842. this._radians += (2.0 * Math.PI);
  6843. }
  6844. /**
  6845. * Get value in degrees
  6846. * @returns the Angle value in degrees (float)
  6847. */
  6848. Angle.prototype.degrees = function () {
  6849. return this._radians * 180.0 / Math.PI;
  6850. };
  6851. /**
  6852. * Get value in radians
  6853. * @returns the Angle value in radians (float)
  6854. */
  6855. Angle.prototype.radians = function () {
  6856. return this._radians;
  6857. };
  6858. /**
  6859. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  6860. * @param a defines first vector
  6861. * @param b defines second vector
  6862. * @returns a new Angle
  6863. */
  6864. Angle.BetweenTwoPoints = function (a, b) {
  6865. var delta = b.subtract(a);
  6866. var theta = Math.atan2(delta.y, delta.x);
  6867. return new Angle(theta);
  6868. };
  6869. /**
  6870. * Gets a new Angle object from the given float in radians
  6871. * @param radians defines the angle value in radians
  6872. * @returns a new Angle
  6873. */
  6874. Angle.FromRadians = function (radians) {
  6875. return new Angle(radians);
  6876. };
  6877. /**
  6878. * Gets a new Angle object from the given float in degrees
  6879. * @param degrees defines the angle value in degrees
  6880. * @returns a new Angle
  6881. */
  6882. Angle.FromDegrees = function (degrees) {
  6883. return new Angle(degrees * Math.PI / 180.0);
  6884. };
  6885. return Angle;
  6886. }());
  6887. BABYLON.Angle = Angle;
  6888. var Arc2 = /** @class */ (function () {
  6889. /**
  6890. * Creates an Arc object from the three given points : start, middle and end.
  6891. */
  6892. function Arc2(startPoint, midPoint, endPoint) {
  6893. this.startPoint = startPoint;
  6894. this.midPoint = midPoint;
  6895. this.endPoint = endPoint;
  6896. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  6897. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  6898. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  6899. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  6900. 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);
  6901. this.radius = this.centerPoint.subtract(this.startPoint).length();
  6902. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  6903. var a1 = this.startAngle.degrees();
  6904. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  6905. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  6906. // angles correction
  6907. if (a2 - a1 > +180.0)
  6908. a2 -= 360.0;
  6909. if (a2 - a1 < -180.0)
  6910. a2 += 360.0;
  6911. if (a3 - a2 > +180.0)
  6912. a3 -= 360.0;
  6913. if (a3 - a2 < -180.0)
  6914. a3 += 360.0;
  6915. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  6916. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  6917. }
  6918. return Arc2;
  6919. }());
  6920. BABYLON.Arc2 = Arc2;
  6921. var Path2 = /** @class */ (function () {
  6922. /**
  6923. * Creates a Path2 object from the starting 2D coordinates x and y.
  6924. */
  6925. function Path2(x, y) {
  6926. this._points = new Array();
  6927. this._length = 0.0;
  6928. this.closed = false;
  6929. this._points.push(new Vector2(x, y));
  6930. }
  6931. /**
  6932. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  6933. * Returns the updated Path2.
  6934. */
  6935. Path2.prototype.addLineTo = function (x, y) {
  6936. if (this.closed) {
  6937. return this;
  6938. }
  6939. var newPoint = new Vector2(x, y);
  6940. var previousPoint = this._points[this._points.length - 1];
  6941. this._points.push(newPoint);
  6942. this._length += newPoint.subtract(previousPoint).length();
  6943. return this;
  6944. };
  6945. /**
  6946. * 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.
  6947. * Returns the updated Path2.
  6948. */
  6949. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  6950. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  6951. if (this.closed) {
  6952. return this;
  6953. }
  6954. var startPoint = this._points[this._points.length - 1];
  6955. var midPoint = new Vector2(midX, midY);
  6956. var endPoint = new Vector2(endX, endY);
  6957. var arc = new Arc2(startPoint, midPoint, endPoint);
  6958. var increment = arc.angle.radians() / numberOfSegments;
  6959. if (arc.orientation === Orientation.CW)
  6960. increment *= -1;
  6961. var currentAngle = arc.startAngle.radians() + increment;
  6962. for (var i = 0; i < numberOfSegments; i++) {
  6963. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  6964. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  6965. this.addLineTo(x, y);
  6966. currentAngle += increment;
  6967. }
  6968. return this;
  6969. };
  6970. /**
  6971. * Closes the Path2.
  6972. * Returns the Path2.
  6973. */
  6974. Path2.prototype.close = function () {
  6975. this.closed = true;
  6976. return this;
  6977. };
  6978. /**
  6979. * Returns the Path2 total length (float).
  6980. */
  6981. Path2.prototype.length = function () {
  6982. var result = this._length;
  6983. if (!this.closed) {
  6984. var lastPoint = this._points[this._points.length - 1];
  6985. var firstPoint = this._points[0];
  6986. result += (firstPoint.subtract(lastPoint).length());
  6987. }
  6988. return result;
  6989. };
  6990. /**
  6991. * Returns the Path2 internal array of points.
  6992. */
  6993. Path2.prototype.getPoints = function () {
  6994. return this._points;
  6995. };
  6996. /**
  6997. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  6998. */
  6999. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7000. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7001. return Vector2.Zero();
  7002. }
  7003. var lengthPosition = normalizedLengthPosition * this.length();
  7004. var previousOffset = 0;
  7005. for (var i = 0; i < this._points.length; i++) {
  7006. var j = (i + 1) % this._points.length;
  7007. var a = this._points[i];
  7008. var b = this._points[j];
  7009. var bToA = b.subtract(a);
  7010. var nextOffset = (bToA.length() + previousOffset);
  7011. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7012. var dir = bToA.normalize();
  7013. var localOffset = lengthPosition - previousOffset;
  7014. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7015. }
  7016. previousOffset = nextOffset;
  7017. }
  7018. return Vector2.Zero();
  7019. };
  7020. /**
  7021. * Returns a new Path2 starting at the coordinates (x, y).
  7022. */
  7023. Path2.StartingAt = function (x, y) {
  7024. return new Path2(x, y);
  7025. };
  7026. return Path2;
  7027. }());
  7028. BABYLON.Path2 = Path2;
  7029. var Path3D = /** @class */ (function () {
  7030. /**
  7031. * new Path3D(path, normal, raw)
  7032. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7033. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7034. * path : an array of Vector3, the curve axis of the Path3D
  7035. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7036. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7037. */
  7038. function Path3D(path, firstNormal, raw) {
  7039. if (firstNormal === void 0) { firstNormal = null; }
  7040. this.path = path;
  7041. this._curve = new Array();
  7042. this._distances = new Array();
  7043. this._tangents = new Array();
  7044. this._normals = new Array();
  7045. this._binormals = new Array();
  7046. for (var p = 0; p < path.length; p++) {
  7047. this._curve[p] = path[p].clone(); // hard copy
  7048. }
  7049. this._raw = raw || false;
  7050. this._compute(firstNormal);
  7051. }
  7052. /**
  7053. * Returns the Path3D array of successive Vector3 designing its curve.
  7054. */
  7055. Path3D.prototype.getCurve = function () {
  7056. return this._curve;
  7057. };
  7058. /**
  7059. * Returns an array populated with tangent vectors on each Path3D curve point.
  7060. */
  7061. Path3D.prototype.getTangents = function () {
  7062. return this._tangents;
  7063. };
  7064. /**
  7065. * Returns an array populated with normal vectors on each Path3D curve point.
  7066. */
  7067. Path3D.prototype.getNormals = function () {
  7068. return this._normals;
  7069. };
  7070. /**
  7071. * Returns an array populated with binormal vectors on each Path3D curve point.
  7072. */
  7073. Path3D.prototype.getBinormals = function () {
  7074. return this._binormals;
  7075. };
  7076. /**
  7077. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7078. */
  7079. Path3D.prototype.getDistances = function () {
  7080. return this._distances;
  7081. };
  7082. /**
  7083. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7084. * Returns the same object updated.
  7085. */
  7086. Path3D.prototype.update = function (path, firstNormal) {
  7087. if (firstNormal === void 0) { firstNormal = null; }
  7088. for (var p = 0; p < path.length; p++) {
  7089. this._curve[p].x = path[p].x;
  7090. this._curve[p].y = path[p].y;
  7091. this._curve[p].z = path[p].z;
  7092. }
  7093. this._compute(firstNormal);
  7094. return this;
  7095. };
  7096. // private function compute() : computes tangents, normals and binormals
  7097. Path3D.prototype._compute = function (firstNormal) {
  7098. var l = this._curve.length;
  7099. // first and last tangents
  7100. this._tangents[0] = this._getFirstNonNullVector(0);
  7101. if (!this._raw) {
  7102. this._tangents[0].normalize();
  7103. }
  7104. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7105. if (!this._raw) {
  7106. this._tangents[l - 1].normalize();
  7107. }
  7108. // normals and binormals at first point : arbitrary vector with _normalVector()
  7109. var tg0 = this._tangents[0];
  7110. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7111. this._normals[0] = pp0;
  7112. if (!this._raw) {
  7113. this._normals[0].normalize();
  7114. }
  7115. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7116. if (!this._raw) {
  7117. this._binormals[0].normalize();
  7118. }
  7119. this._distances[0] = 0.0;
  7120. // normals and binormals : next points
  7121. var prev; // previous vector (segment)
  7122. var cur; // current vector (segment)
  7123. var curTang; // current tangent
  7124. // previous normal
  7125. var prevBinor; // previous binormal
  7126. for (var i = 1; i < l; i++) {
  7127. // tangents
  7128. prev = this._getLastNonNullVector(i);
  7129. if (i < l - 1) {
  7130. cur = this._getFirstNonNullVector(i);
  7131. this._tangents[i] = prev.add(cur);
  7132. this._tangents[i].normalize();
  7133. }
  7134. this._distances[i] = this._distances[i - 1] + prev.length();
  7135. // normals and binormals
  7136. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7137. curTang = this._tangents[i];
  7138. prevBinor = this._binormals[i - 1];
  7139. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7140. if (!this._raw) {
  7141. this._normals[i].normalize();
  7142. }
  7143. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7144. if (!this._raw) {
  7145. this._binormals[i].normalize();
  7146. }
  7147. }
  7148. };
  7149. // private function getFirstNonNullVector(index)
  7150. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7151. Path3D.prototype._getFirstNonNullVector = function (index) {
  7152. var i = 1;
  7153. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7154. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7155. i++;
  7156. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7157. }
  7158. return nNVector;
  7159. };
  7160. // private function getLastNonNullVector(index)
  7161. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7162. Path3D.prototype._getLastNonNullVector = function (index) {
  7163. var i = 1;
  7164. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7165. while (nLVector.length() === 0 && index > i + 1) {
  7166. i++;
  7167. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7168. }
  7169. return nLVector;
  7170. };
  7171. // private function normalVector(v0, vt, va) :
  7172. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7173. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7174. Path3D.prototype._normalVector = function (v0, vt, va) {
  7175. var normal0;
  7176. var tgl = vt.length();
  7177. if (tgl === 0.0) {
  7178. tgl = 1.0;
  7179. }
  7180. if (va === undefined || va === null) {
  7181. var point;
  7182. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7183. point = new Vector3(0.0, -1.0, 0.0);
  7184. }
  7185. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7186. point = new Vector3(1.0, 0.0, 0.0);
  7187. }
  7188. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7189. point = new Vector3(0.0, 0.0, 1.0);
  7190. }
  7191. else {
  7192. point = Vector3.Zero();
  7193. }
  7194. normal0 = Vector3.Cross(vt, point);
  7195. }
  7196. else {
  7197. normal0 = Vector3.Cross(vt, va);
  7198. Vector3.CrossToRef(normal0, vt, normal0);
  7199. }
  7200. normal0.normalize();
  7201. return normal0;
  7202. };
  7203. return Path3D;
  7204. }());
  7205. BABYLON.Path3D = Path3D;
  7206. var Curve3 = /** @class */ (function () {
  7207. /**
  7208. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7209. * A Curve3 is designed from a series of successive Vector3.
  7210. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7211. */
  7212. function Curve3(points) {
  7213. this._length = 0.0;
  7214. this._points = points;
  7215. this._length = this._computeLength(points);
  7216. }
  7217. /**
  7218. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7219. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7220. * @param v1 (Vector3) the control point
  7221. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7222. * @param nbPoints (integer) the wanted number of points in the curve
  7223. */
  7224. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7225. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7226. var bez = new Array();
  7227. var equation = function (t, val0, val1, val2) {
  7228. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7229. return res;
  7230. };
  7231. for (var i = 0; i <= nbPoints; i++) {
  7232. 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)));
  7233. }
  7234. return new Curve3(bez);
  7235. };
  7236. /**
  7237. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7238. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7239. * @param v1 (Vector3) the first control point
  7240. * @param v2 (Vector3) the second control point
  7241. * @param v3 (Vector3) the end point of the Cubic Bezier
  7242. * @param nbPoints (integer) the wanted number of points in the curve
  7243. */
  7244. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7245. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7246. var bez = new Array();
  7247. var equation = function (t, val0, val1, val2, val3) {
  7248. 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;
  7249. return res;
  7250. };
  7251. for (var i = 0; i <= nbPoints; i++) {
  7252. 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)));
  7253. }
  7254. return new Curve3(bez);
  7255. };
  7256. /**
  7257. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7258. * @param p1 (Vector3) the origin point of the Hermite Spline
  7259. * @param t1 (Vector3) the tangent vector at the origin point
  7260. * @param p2 (Vector3) the end point of the Hermite Spline
  7261. * @param t2 (Vector3) the tangent vector at the end point
  7262. * @param nbPoints (integer) the wanted number of points in the curve
  7263. */
  7264. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7265. var hermite = new Array();
  7266. var step = 1.0 / nbPoints;
  7267. for (var i = 0; i <= nbPoints; i++) {
  7268. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7269. }
  7270. return new Curve3(hermite);
  7271. };
  7272. /**
  7273. * Returns a Curve3 object along a CatmullRom Spline curve :
  7274. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  7275. * @param nbPoints (integer) the wanted number of points between each curve control points.
  7276. */
  7277. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  7278. var totalPoints = new Array();
  7279. totalPoints.push(points[0].clone());
  7280. Array.prototype.push.apply(totalPoints, points);
  7281. totalPoints.push(points[points.length - 1].clone());
  7282. var catmullRom = new Array();
  7283. var step = 1.0 / nbPoints;
  7284. var amount = 0.0;
  7285. for (var i = 0; i < totalPoints.length - 3; i++) {
  7286. amount = 0;
  7287. for (var c = 0; c < nbPoints; c++) {
  7288. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7289. amount += step;
  7290. }
  7291. }
  7292. i--;
  7293. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7294. return new Curve3(catmullRom);
  7295. };
  7296. /**
  7297. * Returns the Curve3 stored array of successive Vector3
  7298. */
  7299. Curve3.prototype.getPoints = function () {
  7300. return this._points;
  7301. };
  7302. /**
  7303. * Returns the computed length (float) of the curve.
  7304. */
  7305. Curve3.prototype.length = function () {
  7306. return this._length;
  7307. };
  7308. /**
  7309. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7310. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7311. * curveA and curveB keep unchanged.
  7312. */
  7313. Curve3.prototype.continue = function (curve) {
  7314. var lastPoint = this._points[this._points.length - 1];
  7315. var continuedPoints = this._points.slice();
  7316. var curvePoints = curve.getPoints();
  7317. for (var i = 1; i < curvePoints.length; i++) {
  7318. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7319. }
  7320. var continuedCurve = new Curve3(continuedPoints);
  7321. return continuedCurve;
  7322. };
  7323. Curve3.prototype._computeLength = function (path) {
  7324. var l = 0;
  7325. for (var i = 1; i < path.length; i++) {
  7326. l += (path[i].subtract(path[i - 1])).length();
  7327. }
  7328. return l;
  7329. };
  7330. return Curve3;
  7331. }());
  7332. BABYLON.Curve3 = Curve3;
  7333. // Vertex formats
  7334. var PositionNormalVertex = /** @class */ (function () {
  7335. function PositionNormalVertex(position, normal) {
  7336. if (position === void 0) { position = Vector3.Zero(); }
  7337. if (normal === void 0) { normal = Vector3.Up(); }
  7338. this.position = position;
  7339. this.normal = normal;
  7340. }
  7341. PositionNormalVertex.prototype.clone = function () {
  7342. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7343. };
  7344. return PositionNormalVertex;
  7345. }());
  7346. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7347. var PositionNormalTextureVertex = /** @class */ (function () {
  7348. function PositionNormalTextureVertex(position, normal, uv) {
  7349. if (position === void 0) { position = Vector3.Zero(); }
  7350. if (normal === void 0) { normal = Vector3.Up(); }
  7351. if (uv === void 0) { uv = Vector2.Zero(); }
  7352. this.position = position;
  7353. this.normal = normal;
  7354. this.uv = uv;
  7355. }
  7356. PositionNormalTextureVertex.prototype.clone = function () {
  7357. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7358. };
  7359. return PositionNormalTextureVertex;
  7360. }());
  7361. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7362. // Temporary pre-allocated objects for engine internal use
  7363. // usage in any internal function :
  7364. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7365. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7366. var Tmp = /** @class */ (function () {
  7367. function Tmp() {
  7368. }
  7369. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7370. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7371. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7372. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7373. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7374. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7375. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7376. Matrix.Zero(), Matrix.Zero(),
  7377. Matrix.Zero(), Matrix.Zero(),
  7378. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7379. return Tmp;
  7380. }());
  7381. BABYLON.Tmp = Tmp;
  7382. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7383. var MathTmp = /** @class */ (function () {
  7384. function MathTmp() {
  7385. }
  7386. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7387. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7388. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7389. return MathTmp;
  7390. }());
  7391. })(BABYLON || (BABYLON = {}));
  7392. //# sourceMappingURL=babylon.math.js.map
  7393. var BABYLON;
  7394. (function (BABYLON) {
  7395. var Scalar = /** @class */ (function () {
  7396. function Scalar() {
  7397. }
  7398. /**
  7399. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7400. */
  7401. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7402. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7403. var num = a - b;
  7404. return -epsilon <= num && num <= epsilon;
  7405. };
  7406. /**
  7407. * Returns a string : the upper case translation of the number i to hexadecimal.
  7408. */
  7409. Scalar.ToHex = function (i) {
  7410. var str = i.toString(16);
  7411. if (i <= 15) {
  7412. return ("0" + str).toUpperCase();
  7413. }
  7414. return str.toUpperCase();
  7415. };
  7416. /**
  7417. * Returns -1 if value is negative and +1 is value is positive.
  7418. * Returns the value itself if it's equal to zero.
  7419. */
  7420. Scalar.Sign = function (value) {
  7421. value = +value; // convert to a number
  7422. if (value === 0 || isNaN(value))
  7423. return value;
  7424. return value > 0 ? 1 : -1;
  7425. };
  7426. /**
  7427. * Returns the value itself if it's between min and max.
  7428. * Returns min if the value is lower than min.
  7429. * Returns max if the value is greater than max.
  7430. */
  7431. Scalar.Clamp = function (value, min, max) {
  7432. if (min === void 0) { min = 0; }
  7433. if (max === void 0) { max = 1; }
  7434. return Math.min(max, Math.max(min, value));
  7435. };
  7436. /**
  7437. * Returns the log2 of value.
  7438. */
  7439. Scalar.Log2 = function (value) {
  7440. return Math.log(value) * Math.LOG2E;
  7441. };
  7442. /**
  7443. * Loops the value, so that it is never larger than length and never smaller than 0.
  7444. *
  7445. * This is similar to the modulo operator but it works with floating point numbers.
  7446. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7447. * With t = 5 and length = 2.5, the result would be 0.0.
  7448. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7449. */
  7450. Scalar.Repeat = function (value, length) {
  7451. return value - Math.floor(value / length) * length;
  7452. };
  7453. /**
  7454. * Normalize the value between 0.0 and 1.0 using min and max values
  7455. */
  7456. Scalar.Normalize = function (value, min, max) {
  7457. return (value - min) / (max - min);
  7458. };
  7459. /**
  7460. * Denormalize the value from 0.0 and 1.0 using min and max values
  7461. */
  7462. Scalar.Denormalize = function (normalized, min, max) {
  7463. return (normalized * (max - min) + min);
  7464. };
  7465. /**
  7466. * Calculates the shortest difference between two given angles given in degrees.
  7467. */
  7468. Scalar.DeltaAngle = function (current, target) {
  7469. var num = Scalar.Repeat(target - current, 360.0);
  7470. if (num > 180.0) {
  7471. num -= 360.0;
  7472. }
  7473. return num;
  7474. };
  7475. /**
  7476. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7477. *
  7478. * The returned value will move back and forth between 0 and length
  7479. */
  7480. Scalar.PingPong = function (tx, length) {
  7481. var t = Scalar.Repeat(tx, length * 2.0);
  7482. return length - Math.abs(t - length);
  7483. };
  7484. /**
  7485. * Interpolates between min and max with smoothing at the limits.
  7486. *
  7487. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7488. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7489. */
  7490. Scalar.SmoothStep = function (from, to, tx) {
  7491. var t = Scalar.Clamp(tx);
  7492. t = -2.0 * t * t * t + 3.0 * t * t;
  7493. return to * t + from * (1.0 - t);
  7494. };
  7495. /**
  7496. * Moves a value current towards target.
  7497. *
  7498. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7499. * Negative values of maxDelta pushes the value away from target.
  7500. */
  7501. Scalar.MoveTowards = function (current, target, maxDelta) {
  7502. var result = 0;
  7503. if (Math.abs(target - current) <= maxDelta) {
  7504. result = target;
  7505. }
  7506. else {
  7507. result = current + Scalar.Sign(target - current) * maxDelta;
  7508. }
  7509. return result;
  7510. };
  7511. /**
  7512. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7513. *
  7514. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7515. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7516. */
  7517. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7518. var num = Scalar.DeltaAngle(current, target);
  7519. var result = 0;
  7520. if (-maxDelta < num && num < maxDelta) {
  7521. result = target;
  7522. }
  7523. else {
  7524. target = current + num;
  7525. result = Scalar.MoveTowards(current, target, maxDelta);
  7526. }
  7527. return result;
  7528. };
  7529. /**
  7530. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7531. */
  7532. Scalar.Lerp = function (start, end, amount) {
  7533. return start + ((end - start) * amount);
  7534. };
  7535. /**
  7536. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7537. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7538. */
  7539. Scalar.LerpAngle = function (start, end, amount) {
  7540. var num = Scalar.Repeat(end - start, 360.0);
  7541. if (num > 180.0) {
  7542. num -= 360.0;
  7543. }
  7544. return start + num * Scalar.Clamp(amount);
  7545. };
  7546. /**
  7547. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7548. */
  7549. Scalar.InverseLerp = function (a, b, value) {
  7550. var result = 0;
  7551. if (a != b) {
  7552. result = Scalar.Clamp((value - a) / (b - a));
  7553. }
  7554. else {
  7555. result = 0.0;
  7556. }
  7557. return result;
  7558. };
  7559. /**
  7560. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7561. */
  7562. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7563. var squared = amount * amount;
  7564. var cubed = amount * squared;
  7565. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7566. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7567. var part3 = (cubed - (2.0 * squared)) + amount;
  7568. var part4 = cubed - squared;
  7569. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7570. };
  7571. /**
  7572. * Returns a random float number between and min and max values
  7573. */
  7574. Scalar.RandomRange = function (min, max) {
  7575. if (min === max)
  7576. return min;
  7577. return ((Math.random() * (max - min)) + min);
  7578. };
  7579. /**
  7580. * This function returns percentage of a number in a given range.
  7581. *
  7582. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7583. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7584. */
  7585. Scalar.RangeToPercent = function (number, min, max) {
  7586. return ((number - min) / (max - min));
  7587. };
  7588. /**
  7589. * This function returns number that corresponds to the percentage in a given range.
  7590. *
  7591. * PercentToRange(0.34,0,100) will return 34.
  7592. */
  7593. Scalar.PercentToRange = function (percent, min, max) {
  7594. return ((max - min) * percent + min);
  7595. };
  7596. /**
  7597. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7598. * @param angle The angle to normalize in radian.
  7599. * @return The converted angle.
  7600. */
  7601. Scalar.NormalizeRadians = function (angle) {
  7602. // More precise but slower version kept for reference.
  7603. // angle = angle % Tools.TwoPi;
  7604. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7605. //if (angle > Math.PI) {
  7606. // angle -= Tools.TwoPi;
  7607. //}
  7608. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7609. return angle;
  7610. };
  7611. /**
  7612. * Two pi constants convenient for computation.
  7613. */
  7614. Scalar.TwoPi = Math.PI * 2;
  7615. return Scalar;
  7616. }());
  7617. BABYLON.Scalar = Scalar;
  7618. })(BABYLON || (BABYLON = {}));
  7619. //# sourceMappingURL=babylon.math.scalar.js.map
  7620. //# sourceMappingURL=babylon.mixins.js.map
  7621. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7622. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7623. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7624. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7625. //# sourceMappingURL=babylon.webgl2.js.map
  7626. var BABYLON;
  7627. (function (BABYLON) {
  7628. var __decoratorInitialStore = {};
  7629. var __mergedStore = {};
  7630. var _copySource = function (creationFunction, source, instanciate) {
  7631. var destination = creationFunction();
  7632. // Tags
  7633. if (BABYLON.Tags) {
  7634. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7635. }
  7636. var classStore = getMergedStore(destination);
  7637. // Properties
  7638. for (var property in classStore) {
  7639. var propertyDescriptor = classStore[property];
  7640. var sourceProperty = source[property];
  7641. var propertyType = propertyDescriptor.type;
  7642. if (sourceProperty !== undefined && sourceProperty !== null) {
  7643. switch (propertyType) {
  7644. case 0: // Value
  7645. case 6: // Mesh reference
  7646. case 11: // Camera reference
  7647. destination[property] = sourceProperty;
  7648. break;
  7649. case 1: // Texture
  7650. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7651. break;
  7652. case 2: // Color3
  7653. case 3: // FresnelParameters
  7654. case 4: // Vector2
  7655. case 5: // Vector3
  7656. case 7: // Color Curves
  7657. case 10: // Quaternion
  7658. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7659. break;
  7660. }
  7661. }
  7662. }
  7663. return destination;
  7664. };
  7665. function getDirectStore(target) {
  7666. var classKey = target.getClassName();
  7667. if (!__decoratorInitialStore[classKey]) {
  7668. __decoratorInitialStore[classKey] = {};
  7669. }
  7670. return __decoratorInitialStore[classKey];
  7671. }
  7672. /**
  7673. * Return the list of properties flagged as serializable
  7674. * @param target: host object
  7675. */
  7676. function getMergedStore(target) {
  7677. var classKey = target.getClassName();
  7678. if (__mergedStore[classKey]) {
  7679. return __mergedStore[classKey];
  7680. }
  7681. __mergedStore[classKey] = {};
  7682. var store = __mergedStore[classKey];
  7683. var currentTarget = target;
  7684. var currentKey = classKey;
  7685. while (currentKey) {
  7686. var initialStore = __decoratorInitialStore[currentKey];
  7687. for (var property in initialStore) {
  7688. store[property] = initialStore[property];
  7689. }
  7690. var parent_1 = void 0;
  7691. var done = false;
  7692. do {
  7693. parent_1 = Object.getPrototypeOf(currentTarget);
  7694. if (!parent_1.getClassName) {
  7695. done = true;
  7696. break;
  7697. }
  7698. if (parent_1.getClassName() !== currentKey) {
  7699. break;
  7700. }
  7701. currentTarget = parent_1;
  7702. } while (parent_1);
  7703. if (done) {
  7704. break;
  7705. }
  7706. currentKey = parent_1.getClassName();
  7707. currentTarget = parent_1;
  7708. }
  7709. return store;
  7710. }
  7711. function generateSerializableMember(type, sourceName) {
  7712. return function (target, propertyKey) {
  7713. var classStore = getDirectStore(target);
  7714. if (!classStore[propertyKey]) {
  7715. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7716. }
  7717. };
  7718. }
  7719. function generateExpandMember(setCallback, targetKey) {
  7720. if (targetKey === void 0) { targetKey = null; }
  7721. return function (target, propertyKey) {
  7722. var key = targetKey || ("_" + propertyKey);
  7723. Object.defineProperty(target, propertyKey, {
  7724. get: function () {
  7725. return this[key];
  7726. },
  7727. set: function (value) {
  7728. if (this[key] === value) {
  7729. return;
  7730. }
  7731. this[key] = value;
  7732. target[setCallback].apply(this);
  7733. },
  7734. enumerable: true,
  7735. configurable: true
  7736. });
  7737. };
  7738. }
  7739. function expandToProperty(callback, targetKey) {
  7740. if (targetKey === void 0) { targetKey = null; }
  7741. return generateExpandMember(callback, targetKey);
  7742. }
  7743. BABYLON.expandToProperty = expandToProperty;
  7744. function serialize(sourceName) {
  7745. return generateSerializableMember(0, sourceName); // value member
  7746. }
  7747. BABYLON.serialize = serialize;
  7748. function serializeAsTexture(sourceName) {
  7749. return generateSerializableMember(1, sourceName); // texture member
  7750. }
  7751. BABYLON.serializeAsTexture = serializeAsTexture;
  7752. function serializeAsColor3(sourceName) {
  7753. return generateSerializableMember(2, sourceName); // color3 member
  7754. }
  7755. BABYLON.serializeAsColor3 = serializeAsColor3;
  7756. function serializeAsFresnelParameters(sourceName) {
  7757. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7758. }
  7759. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7760. function serializeAsVector2(sourceName) {
  7761. return generateSerializableMember(4, sourceName); // vector2 member
  7762. }
  7763. BABYLON.serializeAsVector2 = serializeAsVector2;
  7764. function serializeAsVector3(sourceName) {
  7765. return generateSerializableMember(5, sourceName); // vector3 member
  7766. }
  7767. BABYLON.serializeAsVector3 = serializeAsVector3;
  7768. function serializeAsMeshReference(sourceName) {
  7769. return generateSerializableMember(6, sourceName); // mesh reference member
  7770. }
  7771. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7772. function serializeAsColorCurves(sourceName) {
  7773. return generateSerializableMember(7, sourceName); // color curves
  7774. }
  7775. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7776. function serializeAsColor4(sourceName) {
  7777. return generateSerializableMember(8, sourceName); // color 4
  7778. }
  7779. BABYLON.serializeAsColor4 = serializeAsColor4;
  7780. function serializeAsImageProcessingConfiguration(sourceName) {
  7781. return generateSerializableMember(9, sourceName); // image processing
  7782. }
  7783. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7784. function serializeAsQuaternion(sourceName) {
  7785. return generateSerializableMember(10, sourceName); // quaternion member
  7786. }
  7787. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7788. /**
  7789. * Decorator used to define property that can be serialized as reference to a camera
  7790. * @param sourceName defines the name of the property to decorate
  7791. */
  7792. function serializeAsCameraReference(sourceName) {
  7793. return generateSerializableMember(11, sourceName); // camera reference member
  7794. }
  7795. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7796. var SerializationHelper = /** @class */ (function () {
  7797. function SerializationHelper() {
  7798. }
  7799. SerializationHelper.Serialize = function (entity, serializationObject) {
  7800. if (!serializationObject) {
  7801. serializationObject = {};
  7802. }
  7803. // Tags
  7804. if (BABYLON.Tags) {
  7805. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7806. }
  7807. var serializedProperties = getMergedStore(entity);
  7808. // Properties
  7809. for (var property in serializedProperties) {
  7810. var propertyDescriptor = serializedProperties[property];
  7811. var targetPropertyName = propertyDescriptor.sourceName || property;
  7812. var propertyType = propertyDescriptor.type;
  7813. var sourceProperty = entity[property];
  7814. if (sourceProperty !== undefined && sourceProperty !== null) {
  7815. switch (propertyType) {
  7816. case 0: // Value
  7817. serializationObject[targetPropertyName] = sourceProperty;
  7818. break;
  7819. case 1: // Texture
  7820. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7821. break;
  7822. case 2: // Color3
  7823. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7824. break;
  7825. case 3: // FresnelParameters
  7826. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7827. break;
  7828. case 4: // Vector2
  7829. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7830. break;
  7831. case 5: // Vector3
  7832. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7833. break;
  7834. case 6: // Mesh reference
  7835. serializationObject[targetPropertyName] = sourceProperty.id;
  7836. break;
  7837. case 7: // Color Curves
  7838. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7839. break;
  7840. case 8: // Color 4
  7841. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7842. break;
  7843. case 9: // Image Processing
  7844. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7845. break;
  7846. case 10: // Quaternion
  7847. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7848. break;
  7849. case 11: // Camera reference
  7850. serializationObject[targetPropertyName] = sourceProperty.id;
  7851. break;
  7852. }
  7853. }
  7854. }
  7855. return serializationObject;
  7856. };
  7857. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7858. if (rootUrl === void 0) { rootUrl = null; }
  7859. var destination = creationFunction();
  7860. if (!rootUrl) {
  7861. rootUrl = "";
  7862. }
  7863. // Tags
  7864. if (BABYLON.Tags) {
  7865. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7866. }
  7867. var classStore = getMergedStore(destination);
  7868. // Properties
  7869. for (var property in classStore) {
  7870. var propertyDescriptor = classStore[property];
  7871. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7872. var propertyType = propertyDescriptor.type;
  7873. if (sourceProperty !== undefined && sourceProperty !== null) {
  7874. var dest = destination;
  7875. switch (propertyType) {
  7876. case 0: // Value
  7877. dest[property] = sourceProperty;
  7878. break;
  7879. case 1: // Texture
  7880. if (scene) {
  7881. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7882. }
  7883. break;
  7884. case 2: // Color3
  7885. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7886. break;
  7887. case 3: // FresnelParameters
  7888. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7889. break;
  7890. case 4: // Vector2
  7891. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  7892. break;
  7893. case 5: // Vector3
  7894. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  7895. break;
  7896. case 6: // Mesh reference
  7897. if (scene) {
  7898. dest[property] = scene.getLastMeshByID(sourceProperty);
  7899. }
  7900. break;
  7901. case 7: // Color Curves
  7902. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  7903. break;
  7904. case 8: // Color 4
  7905. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  7906. break;
  7907. case 9: // Image Processing
  7908. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  7909. break;
  7910. case 10: // Quaternion
  7911. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  7912. break;
  7913. case 11: // Camera reference
  7914. if (scene) {
  7915. dest[property] = scene.getCameraByID(sourceProperty);
  7916. }
  7917. break;
  7918. }
  7919. }
  7920. }
  7921. return destination;
  7922. };
  7923. SerializationHelper.Clone = function (creationFunction, source) {
  7924. return _copySource(creationFunction, source, false);
  7925. };
  7926. SerializationHelper.Instanciate = function (creationFunction, source) {
  7927. return _copySource(creationFunction, source, true);
  7928. };
  7929. return SerializationHelper;
  7930. }());
  7931. BABYLON.SerializationHelper = SerializationHelper;
  7932. })(BABYLON || (BABYLON = {}));
  7933. //# sourceMappingURL=babylon.decorators.js.map
  7934. var BABYLON;
  7935. (function (BABYLON) {
  7936. /**
  7937. * Wrapper class for promise with external resolve and reject.
  7938. */
  7939. var Deferred = /** @class */ (function () {
  7940. /**
  7941. * Constructor for this deferred object.
  7942. */
  7943. function Deferred() {
  7944. var _this = this;
  7945. this.promise = new Promise(function (resolve, reject) {
  7946. _this._resolve = resolve;
  7947. _this._reject = reject;
  7948. });
  7949. }
  7950. Object.defineProperty(Deferred.prototype, "resolve", {
  7951. /**
  7952. * The resolve method of the promise associated with this deferred object.
  7953. */
  7954. get: function () {
  7955. return this._resolve;
  7956. },
  7957. enumerable: true,
  7958. configurable: true
  7959. });
  7960. Object.defineProperty(Deferred.prototype, "reject", {
  7961. /**
  7962. * The reject method of the promise associated with this deferred object.
  7963. */
  7964. get: function () {
  7965. return this._reject;
  7966. },
  7967. enumerable: true,
  7968. configurable: true
  7969. });
  7970. return Deferred;
  7971. }());
  7972. BABYLON.Deferred = Deferred;
  7973. })(BABYLON || (BABYLON = {}));
  7974. //# sourceMappingURL=babylon.deferred.js.map
  7975. var BABYLON;
  7976. (function (BABYLON) {
  7977. /**
  7978. * A class serves as a medium between the observable and its observers
  7979. */
  7980. var EventState = /** @class */ (function () {
  7981. /**
  7982. * Create a new EventState
  7983. * @param mask defines the mask associated with this state
  7984. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7985. * @param target defines the original target of the state
  7986. * @param currentTarget defines the current target of the state
  7987. */
  7988. function EventState(mask, skipNextObservers, target, currentTarget) {
  7989. if (skipNextObservers === void 0) { skipNextObservers = false; }
  7990. this.initalize(mask, skipNextObservers, target, currentTarget);
  7991. }
  7992. /**
  7993. * Initialize the current event state
  7994. * @param mask defines the mask associated with this state
  7995. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  7996. * @param target defines the original target of the state
  7997. * @param currentTarget defines the current target of the state
  7998. * @returns the current event state
  7999. */
  8000. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8001. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8002. this.mask = mask;
  8003. this.skipNextObservers = skipNextObservers;
  8004. this.target = target;
  8005. this.currentTarget = currentTarget;
  8006. return this;
  8007. };
  8008. return EventState;
  8009. }());
  8010. BABYLON.EventState = EventState;
  8011. /**
  8012. * Represent an Observer registered to a given Observable object.
  8013. */
  8014. var Observer = /** @class */ (function () {
  8015. /**
  8016. * Creates a new observer
  8017. * @param callback defines the callback to call when the observer is notified
  8018. * @param mask defines the mask of the observer (used to filter notifications)
  8019. * @param scope defines the current scope used to restore the JS context
  8020. */
  8021. function Observer(
  8022. /**
  8023. * Defines the callback to call when the observer is notified
  8024. */
  8025. callback,
  8026. /**
  8027. * Defines the mask of the observer (used to filter notifications)
  8028. */
  8029. mask,
  8030. /**
  8031. * Defines the current scope used to restore the JS context
  8032. */
  8033. scope) {
  8034. if (scope === void 0) { scope = null; }
  8035. this.callback = callback;
  8036. this.mask = mask;
  8037. this.scope = scope;
  8038. /** @hidden */
  8039. this._willBeUnregistered = false;
  8040. /**
  8041. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8042. */
  8043. this.unregisterOnNextCall = false;
  8044. }
  8045. return Observer;
  8046. }());
  8047. BABYLON.Observer = Observer;
  8048. /**
  8049. * Represent a list of observers registered to multiple Observables object.
  8050. */
  8051. var MultiObserver = /** @class */ (function () {
  8052. function MultiObserver() {
  8053. }
  8054. /**
  8055. * Release associated resources
  8056. */
  8057. MultiObserver.prototype.dispose = function () {
  8058. if (this._observers && this._observables) {
  8059. for (var index = 0; index < this._observers.length; index++) {
  8060. this._observables[index].remove(this._observers[index]);
  8061. }
  8062. }
  8063. this._observers = null;
  8064. this._observables = null;
  8065. };
  8066. /**
  8067. * Raise a callback when one of the observable will notify
  8068. * @param observables defines a list of observables to watch
  8069. * @param callback defines the callback to call on notification
  8070. * @param mask defines the mask used to filter notifications
  8071. * @param scope defines the current scope used to restore the JS context
  8072. * @returns the new MultiObserver
  8073. */
  8074. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8075. if (mask === void 0) { mask = -1; }
  8076. if (scope === void 0) { scope = null; }
  8077. var result = new MultiObserver();
  8078. result._observers = new Array();
  8079. result._observables = observables;
  8080. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8081. var observable = observables_1[_i];
  8082. var observer = observable.add(callback, mask, false, scope);
  8083. if (observer) {
  8084. result._observers.push(observer);
  8085. }
  8086. }
  8087. return result;
  8088. };
  8089. return MultiObserver;
  8090. }());
  8091. BABYLON.MultiObserver = MultiObserver;
  8092. /**
  8093. * The Observable class is a simple implementation of the Observable pattern.
  8094. *
  8095. * 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.
  8096. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8097. * 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).
  8098. * 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.
  8099. */
  8100. var Observable = /** @class */ (function () {
  8101. /**
  8102. * Creates a new observable
  8103. * @param onObserverAdded defines a callback to call when a new observer is added
  8104. */
  8105. function Observable(onObserverAdded) {
  8106. this._observers = new Array();
  8107. this._eventState = new EventState(0);
  8108. if (onObserverAdded) {
  8109. this._onObserverAdded = onObserverAdded;
  8110. }
  8111. }
  8112. /**
  8113. * Create a new Observer with the specified callback
  8114. * @param callback the callback that will be executed for that Observer
  8115. * @param mask the mask used to filter observers
  8116. * @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.
  8117. * @param scope optional scope for the callback to be called from
  8118. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8119. * @returns the new observer created for the callback
  8120. */
  8121. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8122. if (mask === void 0) { mask = -1; }
  8123. if (insertFirst === void 0) { insertFirst = false; }
  8124. if (scope === void 0) { scope = null; }
  8125. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8126. if (!callback) {
  8127. return null;
  8128. }
  8129. var observer = new Observer(callback, mask, scope);
  8130. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8131. if (insertFirst) {
  8132. this._observers.unshift(observer);
  8133. }
  8134. else {
  8135. this._observers.push(observer);
  8136. }
  8137. if (this._onObserverAdded) {
  8138. this._onObserverAdded(observer);
  8139. }
  8140. return observer;
  8141. };
  8142. /**
  8143. * Remove an Observer from the Observable object
  8144. * @param observer the instance of the Observer to remove
  8145. * @returns false if it doesn't belong to this Observable
  8146. */
  8147. Observable.prototype.remove = function (observer) {
  8148. if (!observer) {
  8149. return false;
  8150. }
  8151. var index = this._observers.indexOf(observer);
  8152. if (index !== -1) {
  8153. this._observers.splice(index, 1);
  8154. return true;
  8155. }
  8156. return false;
  8157. };
  8158. /**
  8159. * Remove a callback from the Observable object
  8160. * @param callback the callback to remove
  8161. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8162. * @returns false if it doesn't belong to this Observable
  8163. */
  8164. Observable.prototype.removeCallback = function (callback, scope) {
  8165. for (var index = 0; index < this._observers.length; index++) {
  8166. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8167. this._observers.splice(index, 1);
  8168. return true;
  8169. }
  8170. }
  8171. return false;
  8172. };
  8173. Observable.prototype._deferUnregister = function (observer) {
  8174. var _this = this;
  8175. observer.unregisterOnNextCall = false;
  8176. observer._willBeUnregistered = true;
  8177. BABYLON.Tools.SetImmediate(function () {
  8178. _this.remove(observer);
  8179. });
  8180. };
  8181. /**
  8182. * Notify all Observers by calling their respective callback with the given data
  8183. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8184. * @param eventData defines the data to send to all observers
  8185. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8186. * @param target defines the original target of the state
  8187. * @param currentTarget defines the current target of the state
  8188. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8189. */
  8190. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8191. if (mask === void 0) { mask = -1; }
  8192. if (!this._observers.length) {
  8193. return true;
  8194. }
  8195. var state = this._eventState;
  8196. state.mask = mask;
  8197. state.target = target;
  8198. state.currentTarget = currentTarget;
  8199. state.skipNextObservers = false;
  8200. state.lastReturnValue = eventData;
  8201. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8202. var obs = _a[_i];
  8203. if (obs._willBeUnregistered) {
  8204. continue;
  8205. }
  8206. if (obs.mask & mask) {
  8207. if (obs.scope) {
  8208. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8209. }
  8210. else {
  8211. state.lastReturnValue = obs.callback(eventData, state);
  8212. }
  8213. if (obs.unregisterOnNextCall) {
  8214. this._deferUnregister(obs);
  8215. }
  8216. }
  8217. if (state.skipNextObservers) {
  8218. return false;
  8219. }
  8220. }
  8221. return true;
  8222. };
  8223. /**
  8224. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8225. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8226. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8227. * and it is crucial that all callbacks will be executed.
  8228. * The order of the callbacks is kept, callbacks are not executed parallel.
  8229. *
  8230. * @param eventData The data to be sent to each callback
  8231. * @param mask is used to filter observers defaults to -1
  8232. * @param target defines the callback target (see EventState)
  8233. * @param currentTarget defines he current object in the bubbling phase
  8234. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8235. */
  8236. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8237. var _this = this;
  8238. if (mask === void 0) { mask = -1; }
  8239. // create an empty promise
  8240. var p = Promise.resolve(eventData);
  8241. // no observers? return this promise.
  8242. if (!this._observers.length) {
  8243. return p;
  8244. }
  8245. var state = this._eventState;
  8246. state.mask = mask;
  8247. state.target = target;
  8248. state.currentTarget = currentTarget;
  8249. state.skipNextObservers = false;
  8250. // execute one callback after another (not using Promise.all, the order is important)
  8251. this._observers.forEach(function (obs) {
  8252. if (state.skipNextObservers) {
  8253. return;
  8254. }
  8255. if (obs._willBeUnregistered) {
  8256. return;
  8257. }
  8258. if (obs.mask & mask) {
  8259. if (obs.scope) {
  8260. p = p.then(function (lastReturnedValue) {
  8261. state.lastReturnValue = lastReturnedValue;
  8262. return obs.callback.apply(obs.scope, [eventData, state]);
  8263. });
  8264. }
  8265. else {
  8266. p = p.then(function (lastReturnedValue) {
  8267. state.lastReturnValue = lastReturnedValue;
  8268. return obs.callback(eventData, state);
  8269. });
  8270. }
  8271. if (obs.unregisterOnNextCall) {
  8272. _this._deferUnregister(obs);
  8273. }
  8274. }
  8275. });
  8276. // return the eventData
  8277. return p.then(function () { return eventData; });
  8278. };
  8279. /**
  8280. * Notify a specific observer
  8281. * @param observer defines the observer to notify
  8282. * @param eventData defines the data to be sent to each callback
  8283. * @param mask is used to filter observers defaults to -1
  8284. */
  8285. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8286. if (mask === void 0) { mask = -1; }
  8287. var state = this._eventState;
  8288. state.mask = mask;
  8289. state.skipNextObservers = false;
  8290. observer.callback(eventData, state);
  8291. };
  8292. /**
  8293. * Gets a boolean indicating if the observable has at least one observer
  8294. * @returns true is the Observable has at least one Observer registered
  8295. */
  8296. Observable.prototype.hasObservers = function () {
  8297. return this._observers.length > 0;
  8298. };
  8299. /**
  8300. * Clear the list of observers
  8301. */
  8302. Observable.prototype.clear = function () {
  8303. this._observers = new Array();
  8304. this._onObserverAdded = null;
  8305. };
  8306. /**
  8307. * Clone the current observable
  8308. * @returns a new observable
  8309. */
  8310. Observable.prototype.clone = function () {
  8311. var result = new Observable();
  8312. result._observers = this._observers.slice(0);
  8313. return result;
  8314. };
  8315. /**
  8316. * Does this observable handles observer registered with a given mask
  8317. * @param mask defines the mask to be tested
  8318. * @return whether or not one observer registered with the given mask is handeled
  8319. **/
  8320. Observable.prototype.hasSpecificMask = function (mask) {
  8321. if (mask === void 0) { mask = -1; }
  8322. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8323. var obs = _a[_i];
  8324. if (obs.mask & mask || obs.mask === mask) {
  8325. return true;
  8326. }
  8327. }
  8328. return false;
  8329. };
  8330. return Observable;
  8331. }());
  8332. BABYLON.Observable = Observable;
  8333. })(BABYLON || (BABYLON = {}));
  8334. //# sourceMappingURL=babylon.observable.js.map
  8335. var BABYLON;
  8336. (function (BABYLON) {
  8337. var SmartArray = /** @class */ (function () {
  8338. function SmartArray(capacity) {
  8339. this.length = 0;
  8340. this.data = new Array(capacity);
  8341. this._id = SmartArray._GlobalId++;
  8342. }
  8343. SmartArray.prototype.push = function (value) {
  8344. this.data[this.length++] = value;
  8345. if (this.length > this.data.length) {
  8346. this.data.length *= 2;
  8347. }
  8348. };
  8349. SmartArray.prototype.forEach = function (func) {
  8350. for (var index = 0; index < this.length; index++) {
  8351. func(this.data[index]);
  8352. }
  8353. };
  8354. SmartArray.prototype.sort = function (compareFn) {
  8355. this.data.sort(compareFn);
  8356. };
  8357. SmartArray.prototype.reset = function () {
  8358. this.length = 0;
  8359. };
  8360. SmartArray.prototype.dispose = function () {
  8361. this.reset();
  8362. if (this.data) {
  8363. this.data.length = 0;
  8364. this.data = [];
  8365. }
  8366. };
  8367. SmartArray.prototype.concat = function (array) {
  8368. if (array.length === 0) {
  8369. return;
  8370. }
  8371. if (this.length + array.length > this.data.length) {
  8372. this.data.length = (this.length + array.length) * 2;
  8373. }
  8374. for (var index = 0; index < array.length; index++) {
  8375. this.data[this.length++] = (array.data || array)[index];
  8376. }
  8377. };
  8378. SmartArray.prototype.indexOf = function (value) {
  8379. var position = this.data.indexOf(value);
  8380. if (position >= this.length) {
  8381. return -1;
  8382. }
  8383. return position;
  8384. };
  8385. SmartArray.prototype.contains = function (value) {
  8386. return this.data.indexOf(value) !== -1;
  8387. };
  8388. // Statics
  8389. SmartArray._GlobalId = 0;
  8390. return SmartArray;
  8391. }());
  8392. BABYLON.SmartArray = SmartArray;
  8393. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8394. __extends(SmartArrayNoDuplicate, _super);
  8395. function SmartArrayNoDuplicate() {
  8396. var _this = _super !== null && _super.apply(this, arguments) || this;
  8397. _this._duplicateId = 0;
  8398. return _this;
  8399. }
  8400. SmartArrayNoDuplicate.prototype.push = function (value) {
  8401. _super.prototype.push.call(this, value);
  8402. if (!value.__smartArrayFlags) {
  8403. value.__smartArrayFlags = {};
  8404. }
  8405. value.__smartArrayFlags[this._id] = this._duplicateId;
  8406. };
  8407. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8408. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8409. return false;
  8410. }
  8411. this.push(value);
  8412. return true;
  8413. };
  8414. SmartArrayNoDuplicate.prototype.reset = function () {
  8415. _super.prototype.reset.call(this);
  8416. this._duplicateId++;
  8417. };
  8418. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8419. if (array.length === 0) {
  8420. return;
  8421. }
  8422. if (this.length + array.length > this.data.length) {
  8423. this.data.length = (this.length + array.length) * 2;
  8424. }
  8425. for (var index = 0; index < array.length; index++) {
  8426. var item = (array.data || array)[index];
  8427. this.pushNoDuplicate(item);
  8428. }
  8429. };
  8430. return SmartArrayNoDuplicate;
  8431. }(SmartArray));
  8432. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8433. })(BABYLON || (BABYLON = {}));
  8434. //# sourceMappingURL=babylon.smartArray.js.map
  8435. var BABYLON;
  8436. (function (BABYLON) {
  8437. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8438. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8439. var LoadFileError = /** @class */ (function (_super) {
  8440. __extends(LoadFileError, _super);
  8441. function LoadFileError(message, request) {
  8442. var _this = _super.call(this, message) || this;
  8443. _this.request = request;
  8444. _this.name = "LoadFileError";
  8445. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8446. return _this;
  8447. }
  8448. // Polyfill for Object.setPrototypeOf if necessary.
  8449. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8450. return LoadFileError;
  8451. }(Error));
  8452. BABYLON.LoadFileError = LoadFileError;
  8453. var RetryStrategy = /** @class */ (function () {
  8454. function RetryStrategy() {
  8455. }
  8456. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8457. if (maxRetries === void 0) { maxRetries = 3; }
  8458. if (baseInterval === void 0) { baseInterval = 500; }
  8459. return function (url, request, retryIndex) {
  8460. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8461. return -1;
  8462. }
  8463. return Math.pow(2, retryIndex) * baseInterval;
  8464. };
  8465. };
  8466. return RetryStrategy;
  8467. }());
  8468. BABYLON.RetryStrategy = RetryStrategy;
  8469. // Screenshots
  8470. var screenshotCanvas;
  8471. var cloneValue = function (source, destinationObject) {
  8472. if (!source)
  8473. return null;
  8474. if (source instanceof BABYLON.Mesh) {
  8475. return null;
  8476. }
  8477. if (source instanceof BABYLON.SubMesh) {
  8478. return source.clone(destinationObject);
  8479. }
  8480. else if (source.clone) {
  8481. return source.clone();
  8482. }
  8483. return null;
  8484. };
  8485. var Tools = /** @class */ (function () {
  8486. function Tools() {
  8487. }
  8488. /**
  8489. * Interpolates between a and b via alpha
  8490. * @param a The lower value (returned when alpha = 0)
  8491. * @param b The upper value (returned when alpha = 1)
  8492. * @param alpha The interpolation-factor
  8493. * @return The mixed value
  8494. */
  8495. Tools.Mix = function (a, b, alpha) {
  8496. return a * (1 - alpha) + b * alpha;
  8497. };
  8498. Tools.Instantiate = function (className) {
  8499. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8500. return Tools.RegisteredExternalClasses[className];
  8501. }
  8502. var arr = className.split(".");
  8503. var fn = (window || this);
  8504. for (var i = 0, len = arr.length; i < len; i++) {
  8505. fn = fn[arr[i]];
  8506. }
  8507. if (typeof fn !== "function") {
  8508. return null;
  8509. }
  8510. return fn;
  8511. };
  8512. /**
  8513. * Provides a slice function that will work even on IE
  8514. * @param data defines the array to slice
  8515. * @param start defines the start of the data (optional)
  8516. * @param end defines the end of the data (optional)
  8517. * @returns the new sliced array
  8518. */
  8519. Tools.Slice = function (data, start, end) {
  8520. if (data.slice) {
  8521. return data.slice(start, end);
  8522. }
  8523. return Array.prototype.slice.call(data, start, end);
  8524. };
  8525. Tools.SetImmediate = function (action) {
  8526. if (window.setImmediate) {
  8527. window.setImmediate(action);
  8528. }
  8529. else {
  8530. setTimeout(action, 1);
  8531. }
  8532. };
  8533. Tools.IsExponentOfTwo = function (value) {
  8534. var count = 1;
  8535. do {
  8536. count *= 2;
  8537. } while (count < value);
  8538. return count === value;
  8539. };
  8540. /**
  8541. * Returns the nearest 32-bit single precision float representation of a Number
  8542. * @param value A Number. If the parameter is of a different type, it will get converted
  8543. * to a number or to NaN if it cannot be converted
  8544. * @returns number
  8545. */
  8546. Tools.FloatRound = function (value) {
  8547. if (Math.fround) {
  8548. return Math.fround(value);
  8549. }
  8550. return (Tools._tmpFloatArray[0] = value);
  8551. };
  8552. /**
  8553. * Find the next highest power of two.
  8554. * @param x Number to start search from.
  8555. * @return Next highest power of two.
  8556. */
  8557. Tools.CeilingPOT = function (x) {
  8558. x--;
  8559. x |= x >> 1;
  8560. x |= x >> 2;
  8561. x |= x >> 4;
  8562. x |= x >> 8;
  8563. x |= x >> 16;
  8564. x++;
  8565. return x;
  8566. };
  8567. /**
  8568. * Find the next lowest power of two.
  8569. * @param x Number to start search from.
  8570. * @return Next lowest power of two.
  8571. */
  8572. Tools.FloorPOT = function (x) {
  8573. x = x | (x >> 1);
  8574. x = x | (x >> 2);
  8575. x = x | (x >> 4);
  8576. x = x | (x >> 8);
  8577. x = x | (x >> 16);
  8578. return x - (x >> 1);
  8579. };
  8580. /**
  8581. * Find the nearest power of two.
  8582. * @param x Number to start search from.
  8583. * @return Next nearest power of two.
  8584. */
  8585. Tools.NearestPOT = function (x) {
  8586. var c = Tools.CeilingPOT(x);
  8587. var f = Tools.FloorPOT(x);
  8588. return (c - x) > (x - f) ? f : c;
  8589. };
  8590. Tools.GetExponentOfTwo = function (value, max, mode) {
  8591. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8592. var pot;
  8593. switch (mode) {
  8594. case BABYLON.Engine.SCALEMODE_FLOOR:
  8595. pot = Tools.FloorPOT(value);
  8596. break;
  8597. case BABYLON.Engine.SCALEMODE_NEAREST:
  8598. pot = Tools.NearestPOT(value);
  8599. break;
  8600. case BABYLON.Engine.SCALEMODE_CEILING:
  8601. default:
  8602. pot = Tools.CeilingPOT(value);
  8603. break;
  8604. }
  8605. return Math.min(pot, max);
  8606. };
  8607. Tools.GetFilename = function (path) {
  8608. var index = path.lastIndexOf("/");
  8609. if (index < 0)
  8610. return path;
  8611. return path.substring(index + 1);
  8612. };
  8613. /**
  8614. * Extracts the "folder" part of a path (everything before the filename).
  8615. * @param uri The URI to extract the info from
  8616. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8617. * @returns The "folder" part of the path
  8618. */
  8619. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8620. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8621. var index = uri.lastIndexOf("/");
  8622. if (index < 0) {
  8623. if (returnUnchangedIfNoSlash) {
  8624. return uri;
  8625. }
  8626. return "";
  8627. }
  8628. return uri.substring(0, index + 1);
  8629. };
  8630. Tools.GetDOMTextContent = function (element) {
  8631. var result = "";
  8632. var child = element.firstChild;
  8633. while (child) {
  8634. if (child.nodeType === 3) {
  8635. result += child.textContent;
  8636. }
  8637. child = child.nextSibling;
  8638. }
  8639. return result;
  8640. };
  8641. Tools.ToDegrees = function (angle) {
  8642. return angle * 180 / Math.PI;
  8643. };
  8644. Tools.ToRadians = function (angle) {
  8645. return angle * Math.PI / 180;
  8646. };
  8647. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8648. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8649. var output = "";
  8650. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8651. var i = 0;
  8652. var bytes = new Uint8Array(buffer);
  8653. while (i < bytes.length) {
  8654. chr1 = bytes[i++];
  8655. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8656. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8657. enc1 = chr1 >> 2;
  8658. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8659. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8660. enc4 = chr3 & 63;
  8661. if (isNaN(chr2)) {
  8662. enc3 = enc4 = 64;
  8663. }
  8664. else if (isNaN(chr3)) {
  8665. enc4 = 64;
  8666. }
  8667. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8668. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8669. }
  8670. return "data:image/png;base64," + output;
  8671. };
  8672. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8673. if (bias === void 0) { bias = null; }
  8674. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8675. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8676. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8677. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8678. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8679. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8680. }
  8681. if (bias) {
  8682. minimum.x -= minimum.x * bias.x + bias.y;
  8683. minimum.y -= minimum.y * bias.x + bias.y;
  8684. minimum.z -= minimum.z * bias.x + bias.y;
  8685. maximum.x += maximum.x * bias.x + bias.y;
  8686. maximum.y += maximum.y * bias.x + bias.y;
  8687. maximum.z += maximum.z * bias.x + bias.y;
  8688. }
  8689. return {
  8690. minimum: minimum,
  8691. maximum: maximum
  8692. };
  8693. };
  8694. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8695. if (bias === void 0) { bias = null; }
  8696. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8697. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8698. if (!stride) {
  8699. stride = 3;
  8700. }
  8701. for (var index = start; index < start + count; index++) {
  8702. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8703. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8704. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8705. }
  8706. if (bias) {
  8707. minimum.x -= minimum.x * bias.x + bias.y;
  8708. minimum.y -= minimum.y * bias.x + bias.y;
  8709. minimum.z -= minimum.z * bias.x + bias.y;
  8710. maximum.x += maximum.x * bias.x + bias.y;
  8711. maximum.y += maximum.y * bias.x + bias.y;
  8712. maximum.z += maximum.z * bias.x + bias.y;
  8713. }
  8714. return {
  8715. minimum: minimum,
  8716. maximum: maximum
  8717. };
  8718. };
  8719. Tools.Vector2ArrayFeeder = function (array) {
  8720. return function (index) {
  8721. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8722. var length = isFloatArray ? array.length / 2 : array.length;
  8723. if (index >= length) {
  8724. return null;
  8725. }
  8726. if (isFloatArray) {
  8727. var fa = array;
  8728. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8729. }
  8730. var a = array;
  8731. return a[index];
  8732. };
  8733. };
  8734. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8735. if (bias === void 0) { bias = null; }
  8736. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8737. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8738. var i = 0;
  8739. var cur = feeder(i++);
  8740. while (cur) {
  8741. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8742. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8743. cur = feeder(i++);
  8744. }
  8745. if (bias) {
  8746. minimum.x -= minimum.x * bias.x + bias.y;
  8747. minimum.y -= minimum.y * bias.x + bias.y;
  8748. maximum.x += maximum.x * bias.x + bias.y;
  8749. maximum.y += maximum.y * bias.x + bias.y;
  8750. }
  8751. return {
  8752. minimum: minimum,
  8753. maximum: maximum
  8754. };
  8755. };
  8756. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8757. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8758. return null;
  8759. return Array.isArray(obj) ? obj : [obj];
  8760. };
  8761. // Misc.
  8762. Tools.GetPointerPrefix = function () {
  8763. var eventPrefix = "pointer";
  8764. // Check if pointer events are supported
  8765. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8766. eventPrefix = "mouse";
  8767. }
  8768. return eventPrefix;
  8769. };
  8770. /**
  8771. * @param func - the function to be called
  8772. * @param requester - the object that will request the next frame. Falls back to window.
  8773. */
  8774. Tools.QueueNewFrame = function (func, requester) {
  8775. if (!Tools.IsWindowObjectExist()) {
  8776. return setTimeout(func, 16);
  8777. }
  8778. if (!requester) {
  8779. requester = window;
  8780. }
  8781. if (requester.requestAnimationFrame) {
  8782. return requester.requestAnimationFrame(func);
  8783. }
  8784. else if (requester.msRequestAnimationFrame) {
  8785. return requester.msRequestAnimationFrame(func);
  8786. }
  8787. else if (requester.webkitRequestAnimationFrame) {
  8788. return requester.webkitRequestAnimationFrame(func);
  8789. }
  8790. else if (requester.mozRequestAnimationFrame) {
  8791. return requester.mozRequestAnimationFrame(func);
  8792. }
  8793. else if (requester.oRequestAnimationFrame) {
  8794. return requester.oRequestAnimationFrame(func);
  8795. }
  8796. else {
  8797. return window.setTimeout(func, 16);
  8798. }
  8799. };
  8800. Tools.RequestFullscreen = function (element) {
  8801. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8802. if (!requestFunction)
  8803. return;
  8804. requestFunction.call(element);
  8805. };
  8806. Tools.ExitFullscreen = function () {
  8807. if (document.exitFullscreen) {
  8808. document.exitFullscreen();
  8809. }
  8810. else if (document.mozCancelFullScreen) {
  8811. document.mozCancelFullScreen();
  8812. }
  8813. else if (document.webkitCancelFullScreen) {
  8814. document.webkitCancelFullScreen();
  8815. }
  8816. else if (document.msCancelFullScreen) {
  8817. document.msCancelFullScreen();
  8818. }
  8819. };
  8820. Tools.SetCorsBehavior = function (url, element) {
  8821. if (url && url.indexOf("data:") === 0) {
  8822. return;
  8823. }
  8824. if (Tools.CorsBehavior) {
  8825. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8826. element.crossOrigin = Tools.CorsBehavior;
  8827. }
  8828. else {
  8829. var result = Tools.CorsBehavior(url);
  8830. if (result) {
  8831. element.crossOrigin = result;
  8832. }
  8833. }
  8834. }
  8835. };
  8836. // External files
  8837. Tools.CleanUrl = function (url) {
  8838. url = url.replace(/#/mg, "%23");
  8839. return url;
  8840. };
  8841. Tools.LoadImage = function (url, onLoad, onError, database) {
  8842. if (url instanceof ArrayBuffer) {
  8843. url = Tools.EncodeArrayBufferTobase64(url);
  8844. }
  8845. url = Tools.CleanUrl(url);
  8846. url = Tools.PreprocessUrl(url);
  8847. var img = new Image();
  8848. Tools.SetCorsBehavior(url, img);
  8849. var loadHandler = function () {
  8850. img.removeEventListener("load", loadHandler);
  8851. img.removeEventListener("error", errorHandler);
  8852. onLoad(img);
  8853. };
  8854. var errorHandler = function (err) {
  8855. img.removeEventListener("load", loadHandler);
  8856. img.removeEventListener("error", errorHandler);
  8857. Tools.Error("Error while trying to load image: " + url);
  8858. if (onError) {
  8859. onError("Error while trying to load image: " + url, err);
  8860. }
  8861. };
  8862. img.addEventListener("load", loadHandler);
  8863. img.addEventListener("error", errorHandler);
  8864. var noIndexedDB = function () {
  8865. img.src = url;
  8866. };
  8867. var loadFromIndexedDB = function () {
  8868. if (database) {
  8869. database.loadImageFromDB(url, img);
  8870. }
  8871. };
  8872. //ANY database to do!
  8873. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8874. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8875. }
  8876. else {
  8877. if (url.indexOf("file:") !== -1) {
  8878. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8879. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8880. try {
  8881. var blobURL;
  8882. try {
  8883. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8884. }
  8885. catch (ex) {
  8886. // Chrome doesn't support oneTimeOnly parameter
  8887. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8888. }
  8889. img.src = blobURL;
  8890. }
  8891. catch (e) {
  8892. img.src = "";
  8893. }
  8894. return img;
  8895. }
  8896. }
  8897. noIndexedDB();
  8898. }
  8899. return img;
  8900. };
  8901. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  8902. url = Tools.CleanUrl(url);
  8903. url = Tools.PreprocessUrl(url);
  8904. // If file and file input are set
  8905. if (url.indexOf("file:") !== -1) {
  8906. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  8907. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  8908. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  8909. }
  8910. }
  8911. var loadUrl = Tools.BaseUrl + url;
  8912. var aborted = false;
  8913. var fileRequest = {
  8914. onCompleteObservable: new BABYLON.Observable(),
  8915. abort: function () { return aborted = true; },
  8916. };
  8917. var requestFile = function () {
  8918. var request = new XMLHttpRequest();
  8919. var retryHandle = null;
  8920. fileRequest.abort = function () {
  8921. aborted = true;
  8922. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  8923. request.abort();
  8924. }
  8925. if (retryHandle !== null) {
  8926. clearTimeout(retryHandle);
  8927. retryHandle = null;
  8928. }
  8929. };
  8930. var retryLoop = function (retryIndex) {
  8931. request.open('GET', loadUrl, true);
  8932. if (useArrayBuffer) {
  8933. request.responseType = "arraybuffer";
  8934. }
  8935. if (onProgress) {
  8936. request.addEventListener("progress", onProgress);
  8937. }
  8938. var onLoadEnd = function () {
  8939. request.removeEventListener("loadend", onLoadEnd);
  8940. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8941. fileRequest.onCompleteObservable.clear();
  8942. };
  8943. request.addEventListener("loadend", onLoadEnd);
  8944. var onReadyStateChange = function () {
  8945. if (aborted) {
  8946. return;
  8947. }
  8948. // In case of undefined state in some browsers.
  8949. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  8950. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  8951. request.removeEventListener("readystatechange", onReadyStateChange);
  8952. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  8953. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  8954. return;
  8955. }
  8956. var retryStrategy = Tools.DefaultRetryStrategy;
  8957. if (retryStrategy) {
  8958. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  8959. if (waitTime !== -1) {
  8960. // Prevent the request from completing for retry.
  8961. request.removeEventListener("loadend", onLoadEnd);
  8962. request = new XMLHttpRequest();
  8963. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  8964. return;
  8965. }
  8966. }
  8967. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  8968. if (onError) {
  8969. onError(request, e);
  8970. }
  8971. else {
  8972. throw e;
  8973. }
  8974. }
  8975. };
  8976. request.addEventListener("readystatechange", onReadyStateChange);
  8977. request.send();
  8978. };
  8979. retryLoop(0);
  8980. };
  8981. // Caching all files
  8982. if (database && database.enableSceneOffline) {
  8983. var noIndexedDB_1 = function () {
  8984. if (!aborted) {
  8985. requestFile();
  8986. }
  8987. };
  8988. var loadFromIndexedDB = function () {
  8989. // TODO: database needs to support aborting and should return a IFileRequest
  8990. if (aborted) {
  8991. return;
  8992. }
  8993. if (database) {
  8994. database.loadFileFromDB(url, function (data) {
  8995. if (!aborted) {
  8996. onSuccess(data);
  8997. }
  8998. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  8999. }, onProgress ? function (event) {
  9000. if (!aborted) {
  9001. onProgress(event);
  9002. }
  9003. } : undefined, noIndexedDB_1, useArrayBuffer);
  9004. }
  9005. };
  9006. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9007. }
  9008. else {
  9009. requestFile();
  9010. }
  9011. return fileRequest;
  9012. };
  9013. /**
  9014. * Load a script (identified by an url). When the url returns, the
  9015. * content of this file is added into a new script element, attached to the DOM (body element)
  9016. */
  9017. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9018. var head = document.getElementsByTagName('head')[0];
  9019. var script = document.createElement('script');
  9020. script.type = 'text/javascript';
  9021. script.src = scriptUrl;
  9022. script.onload = function () {
  9023. if (onSuccess) {
  9024. onSuccess();
  9025. }
  9026. };
  9027. script.onerror = function (e) {
  9028. if (onError) {
  9029. onError("Unable to load script '" + scriptUrl + "'", e);
  9030. }
  9031. };
  9032. head.appendChild(script);
  9033. };
  9034. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9035. var reader = new FileReader();
  9036. var request = {
  9037. onCompleteObservable: new BABYLON.Observable(),
  9038. abort: function () { return reader.abort(); },
  9039. };
  9040. reader.onloadend = function (e) {
  9041. request.onCompleteObservable.notifyObservers(request);
  9042. };
  9043. reader.onload = function (e) {
  9044. //target doesn't have result from ts 1.3
  9045. callback(e.target['result']);
  9046. };
  9047. reader.onprogress = progressCallback;
  9048. reader.readAsDataURL(fileToLoad);
  9049. return request;
  9050. };
  9051. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9052. var reader = new FileReader();
  9053. var request = {
  9054. onCompleteObservable: new BABYLON.Observable(),
  9055. abort: function () { return reader.abort(); },
  9056. };
  9057. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9058. reader.onerror = function (e) {
  9059. Tools.Log("Error while reading file: " + fileToLoad.name);
  9060. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9061. };
  9062. reader.onload = function (e) {
  9063. //target doesn't have result from ts 1.3
  9064. callback(e.target['result']);
  9065. };
  9066. if (progressCallBack) {
  9067. reader.onprogress = progressCallBack;
  9068. }
  9069. if (!useArrayBuffer) {
  9070. // Asynchronous read
  9071. reader.readAsText(fileToLoad);
  9072. }
  9073. else {
  9074. reader.readAsArrayBuffer(fileToLoad);
  9075. }
  9076. return request;
  9077. };
  9078. //returns a downloadable url to a file content.
  9079. Tools.FileAsURL = function (content) {
  9080. var fileBlob = new Blob([content]);
  9081. var url = window.URL || window.webkitURL;
  9082. var link = url.createObjectURL(fileBlob);
  9083. return link;
  9084. };
  9085. // Misc.
  9086. Tools.Format = function (value, decimals) {
  9087. if (decimals === void 0) { decimals = 2; }
  9088. return value.toFixed(decimals);
  9089. };
  9090. Tools.CheckExtends = function (v, min, max) {
  9091. if (v.x < min.x)
  9092. min.x = v.x;
  9093. if (v.y < min.y)
  9094. min.y = v.y;
  9095. if (v.z < min.z)
  9096. min.z = v.z;
  9097. if (v.x > max.x)
  9098. max.x = v.x;
  9099. if (v.y > max.y)
  9100. max.y = v.y;
  9101. if (v.z > max.z)
  9102. max.z = v.z;
  9103. };
  9104. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9105. for (var prop in source) {
  9106. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9107. continue;
  9108. }
  9109. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9110. continue;
  9111. }
  9112. var sourceValue = source[prop];
  9113. var typeOfSourceValue = typeof sourceValue;
  9114. if (typeOfSourceValue === "function") {
  9115. continue;
  9116. }
  9117. try {
  9118. if (typeOfSourceValue === "object") {
  9119. if (sourceValue instanceof Array) {
  9120. destination[prop] = [];
  9121. if (sourceValue.length > 0) {
  9122. if (typeof sourceValue[0] == "object") {
  9123. for (var index = 0; index < sourceValue.length; index++) {
  9124. var clonedValue = cloneValue(sourceValue[index], destination);
  9125. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9126. destination[prop].push(clonedValue);
  9127. }
  9128. }
  9129. }
  9130. else {
  9131. destination[prop] = sourceValue.slice(0);
  9132. }
  9133. }
  9134. }
  9135. else {
  9136. destination[prop] = cloneValue(sourceValue, destination);
  9137. }
  9138. }
  9139. else {
  9140. destination[prop] = sourceValue;
  9141. }
  9142. }
  9143. catch (e) {
  9144. // Just ignore error (it could be because of a read-only property)
  9145. }
  9146. }
  9147. };
  9148. Tools.IsEmpty = function (obj) {
  9149. for (var i in obj) {
  9150. if (obj.hasOwnProperty(i)) {
  9151. return false;
  9152. }
  9153. }
  9154. return true;
  9155. };
  9156. Tools.RegisterTopRootEvents = function (events) {
  9157. for (var index = 0; index < events.length; index++) {
  9158. var event = events[index];
  9159. window.addEventListener(event.name, event.handler, false);
  9160. try {
  9161. if (window.parent) {
  9162. window.parent.addEventListener(event.name, event.handler, false);
  9163. }
  9164. }
  9165. catch (e) {
  9166. // Silently fails...
  9167. }
  9168. }
  9169. };
  9170. Tools.UnregisterTopRootEvents = function (events) {
  9171. for (var index = 0; index < events.length; index++) {
  9172. var event = events[index];
  9173. window.removeEventListener(event.name, event.handler);
  9174. try {
  9175. if (window.parent) {
  9176. window.parent.removeEventListener(event.name, event.handler);
  9177. }
  9178. }
  9179. catch (e) {
  9180. // Silently fails...
  9181. }
  9182. }
  9183. };
  9184. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9185. if (mimeType === void 0) { mimeType = "image/png"; }
  9186. // Read the contents of the framebuffer
  9187. var numberOfChannelsByLine = width * 4;
  9188. var halfHeight = height / 2;
  9189. //Reading datas from WebGL
  9190. var data = engine.readPixels(0, 0, width, height);
  9191. //To flip image on Y axis.
  9192. for (var i = 0; i < halfHeight; i++) {
  9193. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9194. var currentCell = j + i * numberOfChannelsByLine;
  9195. var targetLine = height - i - 1;
  9196. var targetCell = j + targetLine * numberOfChannelsByLine;
  9197. var temp = data[currentCell];
  9198. data[currentCell] = data[targetCell];
  9199. data[targetCell] = temp;
  9200. }
  9201. }
  9202. // Create a 2D canvas to store the result
  9203. if (!screenshotCanvas) {
  9204. screenshotCanvas = document.createElement('canvas');
  9205. }
  9206. screenshotCanvas.width = width;
  9207. screenshotCanvas.height = height;
  9208. var context = screenshotCanvas.getContext('2d');
  9209. if (context) {
  9210. // Copy the pixels to a 2D canvas
  9211. var imageData = context.createImageData(width, height);
  9212. var castData = (imageData.data);
  9213. castData.set(data);
  9214. context.putImageData(imageData, 0, 0);
  9215. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9216. }
  9217. };
  9218. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9219. if (mimeType === void 0) { mimeType = "image/png"; }
  9220. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9221. if (successCallback) {
  9222. successCallback(base64Image);
  9223. }
  9224. else {
  9225. // We need HTMLCanvasElement.toBlob for HD screenshots
  9226. if (!screenshotCanvas.toBlob) {
  9227. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9228. screenshotCanvas.toBlob = function (callback, type, quality) {
  9229. var _this = this;
  9230. setTimeout(function () {
  9231. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9232. for (var i = 0; i < len; i++) {
  9233. arr[i] = binStr.charCodeAt(i);
  9234. }
  9235. callback(new Blob([arr], { type: type || 'image/png' }));
  9236. });
  9237. };
  9238. }
  9239. screenshotCanvas.toBlob(function (blob) {
  9240. var url = URL.createObjectURL(blob);
  9241. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9242. if (("download" in document.createElement("a"))) {
  9243. var a = window.document.createElement("a");
  9244. a.href = url;
  9245. if (fileName) {
  9246. a.setAttribute("download", fileName);
  9247. }
  9248. else {
  9249. var date = new Date();
  9250. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9251. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  9252. }
  9253. window.document.body.appendChild(a);
  9254. a.addEventListener("click", function () {
  9255. if (a.parentElement) {
  9256. a.parentElement.removeChild(a);
  9257. }
  9258. });
  9259. a.click();
  9260. }
  9261. else {
  9262. var newWindow = window.open("");
  9263. if (!newWindow)
  9264. return;
  9265. var img = newWindow.document.createElement("img");
  9266. img.onload = function () {
  9267. // no longer need to read the blob so it's revoked
  9268. URL.revokeObjectURL(url);
  9269. };
  9270. img.src = url;
  9271. newWindow.document.body.appendChild(img);
  9272. }
  9273. });
  9274. }
  9275. };
  9276. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9277. if (mimeType === void 0) { mimeType = "image/png"; }
  9278. var width;
  9279. var height;
  9280. // If a precision value is specified
  9281. if (size.precision) {
  9282. width = Math.round(engine.getRenderWidth() * size.precision);
  9283. height = Math.round(width / engine.getAspectRatio(camera));
  9284. }
  9285. else if (size.width && size.height) {
  9286. width = size.width;
  9287. height = size.height;
  9288. }
  9289. //If passing only width, computing height to keep display canvas ratio.
  9290. else if (size.width && !size.height) {
  9291. width = size.width;
  9292. height = Math.round(width / engine.getAspectRatio(camera));
  9293. }
  9294. //If passing only height, computing width to keep display canvas ratio.
  9295. else if (size.height && !size.width) {
  9296. height = size.height;
  9297. width = Math.round(height * engine.getAspectRatio(camera));
  9298. }
  9299. //Assuming here that "size" parameter is a number
  9300. else if (!isNaN(size)) {
  9301. height = size;
  9302. width = size;
  9303. }
  9304. else {
  9305. Tools.Error("Invalid 'size' parameter !");
  9306. return;
  9307. }
  9308. if (!screenshotCanvas) {
  9309. screenshotCanvas = document.createElement('canvas');
  9310. }
  9311. screenshotCanvas.width = width;
  9312. screenshotCanvas.height = height;
  9313. var renderContext = screenshotCanvas.getContext("2d");
  9314. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9315. var newWidth = width;
  9316. var newHeight = newWidth / ratio;
  9317. if (newHeight > height) {
  9318. newHeight = height;
  9319. newWidth = newHeight * ratio;
  9320. }
  9321. var offsetX = Math.max(0, width - newWidth) / 2;
  9322. var offsetY = Math.max(0, height - newHeight) / 2;
  9323. var renderingCanvas = engine.getRenderingCanvas();
  9324. if (renderContext && renderingCanvas) {
  9325. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9326. }
  9327. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9328. };
  9329. /**
  9330. * Generates an image screenshot from the specified camera.
  9331. *
  9332. * @param engine The engine to use for rendering
  9333. * @param camera The camera to use for rendering
  9334. * @param size This parameter can be set to a single number or to an object with the
  9335. * following (optional) properties: precision, width, height. If a single number is passed,
  9336. * it will be used for both width and height. If an object is passed, the screenshot size
  9337. * will be derived from the parameters. The precision property is a multiplier allowing
  9338. * rendering at a higher or lower resolution.
  9339. * @param successCallback The callback receives a single parameter which contains the
  9340. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9341. * src parameter of an <img> to display it.
  9342. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9343. * Check your browser for supported MIME types.
  9344. * @param samples Texture samples (default: 1)
  9345. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9346. * @param fileName A name for for the downloaded file.
  9347. * @constructor
  9348. */
  9349. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9350. if (mimeType === void 0) { mimeType = "image/png"; }
  9351. if (samples === void 0) { samples = 1; }
  9352. if (antialiasing === void 0) { antialiasing = false; }
  9353. var width;
  9354. var height;
  9355. //If a precision value is specified
  9356. if (size.precision) {
  9357. width = Math.round(engine.getRenderWidth() * size.precision);
  9358. height = Math.round(width / engine.getAspectRatio(camera));
  9359. size = { width: width, height: height };
  9360. }
  9361. else if (size.width && size.height) {
  9362. width = size.width;
  9363. height = size.height;
  9364. }
  9365. //If passing only width, computing height to keep display canvas ratio.
  9366. else if (size.width && !size.height) {
  9367. width = size.width;
  9368. height = Math.round(width / engine.getAspectRatio(camera));
  9369. size = { width: width, height: height };
  9370. }
  9371. //If passing only height, computing width to keep display canvas ratio.
  9372. else if (size.height && !size.width) {
  9373. height = size.height;
  9374. width = Math.round(height * engine.getAspectRatio(camera));
  9375. size = { width: width, height: height };
  9376. }
  9377. //Assuming here that "size" parameter is a number
  9378. else if (!isNaN(size)) {
  9379. height = size;
  9380. width = size;
  9381. }
  9382. else {
  9383. Tools.Error("Invalid 'size' parameter !");
  9384. return;
  9385. }
  9386. var scene = camera.getScene();
  9387. var previousCamera = null;
  9388. if (scene.activeCamera !== camera) {
  9389. previousCamera = scene.activeCamera;
  9390. scene.activeCamera = camera;
  9391. }
  9392. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9393. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9394. texture.renderList = null;
  9395. texture.samples = samples;
  9396. if (antialiasing) {
  9397. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9398. }
  9399. texture.onAfterRenderObservable.add(function () {
  9400. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9401. });
  9402. scene.incrementRenderId();
  9403. scene.resetCachedMaterial();
  9404. texture.render(true);
  9405. texture.dispose();
  9406. if (previousCamera) {
  9407. scene.activeCamera = previousCamera;
  9408. }
  9409. camera.getProjectionMatrix(true); // Force cache refresh;
  9410. };
  9411. // XHR response validator for local file scenario
  9412. Tools.ValidateXHRData = function (xhr, dataType) {
  9413. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9414. if (dataType === void 0) { dataType = 7; }
  9415. try {
  9416. if (dataType & 1) {
  9417. if (xhr.responseText && xhr.responseText.length > 0) {
  9418. return true;
  9419. }
  9420. else if (dataType === 1) {
  9421. return false;
  9422. }
  9423. }
  9424. if (dataType & 2) {
  9425. // Check header width and height since there is no "TGA" magic number
  9426. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9427. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9428. return true;
  9429. }
  9430. else if (dataType === 2) {
  9431. return false;
  9432. }
  9433. }
  9434. if (dataType & 4) {
  9435. // Check for the "DDS" magic number
  9436. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9437. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9438. return true;
  9439. }
  9440. else {
  9441. return false;
  9442. }
  9443. }
  9444. }
  9445. catch (e) {
  9446. // Global protection
  9447. }
  9448. return false;
  9449. };
  9450. /**
  9451. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9452. * Be aware Math.random() could cause collisions, but:
  9453. * "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"
  9454. */
  9455. Tools.RandomId = function () {
  9456. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9457. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9458. return v.toString(16);
  9459. });
  9460. };
  9461. /**
  9462. * Test if the given uri is a base64 string.
  9463. * @param uri The uri to test
  9464. * @return True if the uri is a base64 string or false otherwise.
  9465. */
  9466. Tools.IsBase64 = function (uri) {
  9467. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9468. };
  9469. /**
  9470. * Decode the given base64 uri.
  9471. * @param uri The uri to decode
  9472. * @return The decoded base64 data.
  9473. */
  9474. Tools.DecodeBase64 = function (uri) {
  9475. var decodedString = atob(uri.split(",")[1]);
  9476. var bufferLength = decodedString.length;
  9477. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9478. for (var i = 0; i < bufferLength; i++) {
  9479. bufferView[i] = decodedString.charCodeAt(i);
  9480. }
  9481. return bufferView.buffer;
  9482. };
  9483. Object.defineProperty(Tools, "NoneLogLevel", {
  9484. get: function () {
  9485. return Tools._NoneLogLevel;
  9486. },
  9487. enumerable: true,
  9488. configurable: true
  9489. });
  9490. Object.defineProperty(Tools, "MessageLogLevel", {
  9491. get: function () {
  9492. return Tools._MessageLogLevel;
  9493. },
  9494. enumerable: true,
  9495. configurable: true
  9496. });
  9497. Object.defineProperty(Tools, "WarningLogLevel", {
  9498. get: function () {
  9499. return Tools._WarningLogLevel;
  9500. },
  9501. enumerable: true,
  9502. configurable: true
  9503. });
  9504. Object.defineProperty(Tools, "ErrorLogLevel", {
  9505. get: function () {
  9506. return Tools._ErrorLogLevel;
  9507. },
  9508. enumerable: true,
  9509. configurable: true
  9510. });
  9511. Object.defineProperty(Tools, "AllLogLevel", {
  9512. get: function () {
  9513. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9514. },
  9515. enumerable: true,
  9516. configurable: true
  9517. });
  9518. Tools._AddLogEntry = function (entry) {
  9519. Tools._LogCache = entry + Tools._LogCache;
  9520. if (Tools.OnNewCacheEntry) {
  9521. Tools.OnNewCacheEntry(entry);
  9522. }
  9523. };
  9524. Tools._FormatMessage = function (message) {
  9525. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9526. var date = new Date();
  9527. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9528. };
  9529. Tools._LogDisabled = function (message) {
  9530. // nothing to do
  9531. };
  9532. Tools._LogEnabled = function (message) {
  9533. var formattedMessage = Tools._FormatMessage(message);
  9534. console.log("BJS - " + formattedMessage);
  9535. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9536. Tools._AddLogEntry(entry);
  9537. };
  9538. Tools._WarnDisabled = function (message) {
  9539. // nothing to do
  9540. };
  9541. Tools._WarnEnabled = function (message) {
  9542. var formattedMessage = Tools._FormatMessage(message);
  9543. console.warn("BJS - " + formattedMessage);
  9544. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9545. Tools._AddLogEntry(entry);
  9546. };
  9547. Tools._ErrorDisabled = function (message) {
  9548. // nothing to do
  9549. };
  9550. Tools._ErrorEnabled = function (message) {
  9551. Tools.errorsCount++;
  9552. var formattedMessage = Tools._FormatMessage(message);
  9553. console.error("BJS - " + formattedMessage);
  9554. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9555. Tools._AddLogEntry(entry);
  9556. };
  9557. Object.defineProperty(Tools, "LogCache", {
  9558. get: function () {
  9559. return Tools._LogCache;
  9560. },
  9561. enumerable: true,
  9562. configurable: true
  9563. });
  9564. Tools.ClearLogCache = function () {
  9565. Tools._LogCache = "";
  9566. Tools.errorsCount = 0;
  9567. };
  9568. Object.defineProperty(Tools, "LogLevels", {
  9569. set: function (level) {
  9570. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9571. Tools.Log = Tools._LogEnabled;
  9572. }
  9573. else {
  9574. Tools.Log = Tools._LogDisabled;
  9575. }
  9576. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9577. Tools.Warn = Tools._WarnEnabled;
  9578. }
  9579. else {
  9580. Tools.Warn = Tools._WarnDisabled;
  9581. }
  9582. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9583. Tools.Error = Tools._ErrorEnabled;
  9584. }
  9585. else {
  9586. Tools.Error = Tools._ErrorDisabled;
  9587. }
  9588. },
  9589. enumerable: true,
  9590. configurable: true
  9591. });
  9592. Tools.IsWindowObjectExist = function () {
  9593. return (typeof window) !== "undefined";
  9594. };
  9595. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9596. get: function () {
  9597. return Tools._PerformanceNoneLogLevel;
  9598. },
  9599. enumerable: true,
  9600. configurable: true
  9601. });
  9602. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9603. get: function () {
  9604. return Tools._PerformanceUserMarkLogLevel;
  9605. },
  9606. enumerable: true,
  9607. configurable: true
  9608. });
  9609. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9610. get: function () {
  9611. return Tools._PerformanceConsoleLogLevel;
  9612. },
  9613. enumerable: true,
  9614. configurable: true
  9615. });
  9616. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9617. set: function (level) {
  9618. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9619. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9620. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9621. return;
  9622. }
  9623. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9624. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9625. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9626. return;
  9627. }
  9628. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9629. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9630. },
  9631. enumerable: true,
  9632. configurable: true
  9633. });
  9634. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9635. };
  9636. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9637. };
  9638. Tools._StartUserMark = function (counterName, condition) {
  9639. if (condition === void 0) { condition = true; }
  9640. if (!Tools._performance) {
  9641. if (!Tools.IsWindowObjectExist()) {
  9642. return;
  9643. }
  9644. Tools._performance = window.performance;
  9645. }
  9646. if (!condition || !Tools._performance.mark) {
  9647. return;
  9648. }
  9649. Tools._performance.mark(counterName + "-Begin");
  9650. };
  9651. Tools._EndUserMark = function (counterName, condition) {
  9652. if (condition === void 0) { condition = true; }
  9653. if (!condition || !Tools._performance.mark) {
  9654. return;
  9655. }
  9656. Tools._performance.mark(counterName + "-End");
  9657. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9658. };
  9659. Tools._StartPerformanceConsole = function (counterName, condition) {
  9660. if (condition === void 0) { condition = true; }
  9661. if (!condition) {
  9662. return;
  9663. }
  9664. Tools._StartUserMark(counterName, condition);
  9665. if (console.time) {
  9666. console.time(counterName);
  9667. }
  9668. };
  9669. Tools._EndPerformanceConsole = function (counterName, condition) {
  9670. if (condition === void 0) { condition = true; }
  9671. if (!condition) {
  9672. return;
  9673. }
  9674. Tools._EndUserMark(counterName, condition);
  9675. if (console.time) {
  9676. console.timeEnd(counterName);
  9677. }
  9678. };
  9679. Object.defineProperty(Tools, "Now", {
  9680. get: function () {
  9681. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9682. return window.performance.now();
  9683. }
  9684. return Date.now();
  9685. },
  9686. enumerable: true,
  9687. configurable: true
  9688. });
  9689. /**
  9690. * This method will return the name of the class used to create the instance of the given object.
  9691. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9692. * @param object the object to get the class name from
  9693. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9694. */
  9695. Tools.GetClassName = function (object, isType) {
  9696. if (isType === void 0) { isType = false; }
  9697. var name = null;
  9698. if (!isType && object.getClassName) {
  9699. name = object.getClassName();
  9700. }
  9701. else {
  9702. if (object instanceof Object) {
  9703. var classObj = isType ? object : Object.getPrototypeOf(object);
  9704. name = classObj.constructor["__bjsclassName__"];
  9705. }
  9706. if (!name) {
  9707. name = typeof object;
  9708. }
  9709. }
  9710. return name;
  9711. };
  9712. Tools.First = function (array, predicate) {
  9713. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9714. var el = array_1[_i];
  9715. if (predicate(el)) {
  9716. return el;
  9717. }
  9718. }
  9719. return null;
  9720. };
  9721. /**
  9722. * This method will return the name of the full name of the class, including its owning module (if any).
  9723. * 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).
  9724. * @param object the object to get the class name from
  9725. * @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.
  9726. */
  9727. Tools.getFullClassName = function (object, isType) {
  9728. if (isType === void 0) { isType = false; }
  9729. var className = null;
  9730. var moduleName = null;
  9731. if (!isType && object.getClassName) {
  9732. className = object.getClassName();
  9733. }
  9734. else {
  9735. if (object instanceof Object) {
  9736. var classObj = isType ? object : Object.getPrototypeOf(object);
  9737. className = classObj.constructor["__bjsclassName__"];
  9738. moduleName = classObj.constructor["__bjsmoduleName__"];
  9739. }
  9740. if (!className) {
  9741. className = typeof object;
  9742. }
  9743. }
  9744. if (!className) {
  9745. return null;
  9746. }
  9747. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9748. };
  9749. /**
  9750. * 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.
  9751. * @param array
  9752. */
  9753. Tools.arrayOrStringFeeder = function (array) {
  9754. return function (index) {
  9755. if (index >= array.length) {
  9756. return null;
  9757. }
  9758. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9759. if (val && val.getHashCode) {
  9760. val = val.getHashCode();
  9761. }
  9762. if (typeof val === "string") {
  9763. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9764. }
  9765. return val;
  9766. };
  9767. };
  9768. /**
  9769. * Compute the hashCode of a stream of number
  9770. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9771. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9772. * @return the hash code computed
  9773. */
  9774. Tools.hashCodeFromStream = function (feeder) {
  9775. // Based from here: http://stackoverflow.com/a/7616484/802124
  9776. var hash = 0;
  9777. var index = 0;
  9778. var chr = feeder(index++);
  9779. while (chr != null) {
  9780. hash = ((hash << 5) - hash) + chr;
  9781. hash |= 0; // Convert to 32bit integer
  9782. chr = feeder(index++);
  9783. }
  9784. return hash;
  9785. };
  9786. /**
  9787. * Returns a promise that resolves after the given amount of time.
  9788. * @param delay Number of milliseconds to delay
  9789. * @returns Promise that resolves after the given amount of time
  9790. */
  9791. Tools.DelayAsync = function (delay) {
  9792. return new Promise(function (resolve) {
  9793. setTimeout(function () {
  9794. resolve();
  9795. }, delay);
  9796. });
  9797. };
  9798. Tools.BaseUrl = "";
  9799. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9800. /**
  9801. * Default behaviour for cors in the application.
  9802. * It can be a string if the expected behavior is identical in the entire app.
  9803. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9804. */
  9805. Tools.CorsBehavior = "anonymous";
  9806. Tools.UseFallbackTexture = true;
  9807. /**
  9808. * Use this object to register external classes like custom textures or material
  9809. * to allow the laoders to instantiate them
  9810. */
  9811. Tools.RegisteredExternalClasses = {};
  9812. // Used in case of a texture loading problem
  9813. 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";
  9814. Tools._tmpFloatArray = new Float32Array(1);
  9815. Tools.PreprocessUrl = function (url) {
  9816. return url;
  9817. };
  9818. // Logs
  9819. Tools._NoneLogLevel = 0;
  9820. Tools._MessageLogLevel = 1;
  9821. Tools._WarningLogLevel = 2;
  9822. Tools._ErrorLogLevel = 4;
  9823. Tools._LogCache = "";
  9824. Tools.errorsCount = 0;
  9825. Tools.Log = Tools._LogEnabled;
  9826. Tools.Warn = Tools._WarnEnabled;
  9827. Tools.Error = Tools._ErrorEnabled;
  9828. // Performances
  9829. Tools._PerformanceNoneLogLevel = 0;
  9830. Tools._PerformanceUserMarkLogLevel = 1;
  9831. Tools._PerformanceConsoleLogLevel = 2;
  9832. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9833. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9834. return Tools;
  9835. }());
  9836. BABYLON.Tools = Tools;
  9837. /**
  9838. * This class is used to track a performance counter which is number based.
  9839. * The user has access to many properties which give statistics of different nature
  9840. *
  9841. * The implementer can track two kinds of Performance Counter: time and count
  9842. * 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.
  9843. * 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.
  9844. */
  9845. var PerfCounter = /** @class */ (function () {
  9846. function PerfCounter() {
  9847. this._startMonitoringTime = 0;
  9848. this._min = 0;
  9849. this._max = 0;
  9850. this._average = 0;
  9851. this._lastSecAverage = 0;
  9852. this._current = 0;
  9853. this._totalValueCount = 0;
  9854. this._totalAccumulated = 0;
  9855. this._lastSecAccumulated = 0;
  9856. this._lastSecTime = 0;
  9857. this._lastSecValueCount = 0;
  9858. }
  9859. Object.defineProperty(PerfCounter.prototype, "min", {
  9860. /**
  9861. * Returns the smallest value ever
  9862. */
  9863. get: function () {
  9864. return this._min;
  9865. },
  9866. enumerable: true,
  9867. configurable: true
  9868. });
  9869. Object.defineProperty(PerfCounter.prototype, "max", {
  9870. /**
  9871. * Returns the biggest value ever
  9872. */
  9873. get: function () {
  9874. return this._max;
  9875. },
  9876. enumerable: true,
  9877. configurable: true
  9878. });
  9879. Object.defineProperty(PerfCounter.prototype, "average", {
  9880. /**
  9881. * Returns the average value since the performance counter is running
  9882. */
  9883. get: function () {
  9884. return this._average;
  9885. },
  9886. enumerable: true,
  9887. configurable: true
  9888. });
  9889. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9890. /**
  9891. * Returns the average value of the last second the counter was monitored
  9892. */
  9893. get: function () {
  9894. return this._lastSecAverage;
  9895. },
  9896. enumerable: true,
  9897. configurable: true
  9898. });
  9899. Object.defineProperty(PerfCounter.prototype, "current", {
  9900. /**
  9901. * Returns the current value
  9902. */
  9903. get: function () {
  9904. return this._current;
  9905. },
  9906. enumerable: true,
  9907. configurable: true
  9908. });
  9909. Object.defineProperty(PerfCounter.prototype, "total", {
  9910. get: function () {
  9911. return this._totalAccumulated;
  9912. },
  9913. enumerable: true,
  9914. configurable: true
  9915. });
  9916. Object.defineProperty(PerfCounter.prototype, "count", {
  9917. get: function () {
  9918. return this._totalValueCount;
  9919. },
  9920. enumerable: true,
  9921. configurable: true
  9922. });
  9923. /**
  9924. * Call this method to start monitoring a new frame.
  9925. * 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.
  9926. */
  9927. PerfCounter.prototype.fetchNewFrame = function () {
  9928. this._totalValueCount++;
  9929. this._current = 0;
  9930. this._lastSecValueCount++;
  9931. };
  9932. /**
  9933. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  9934. * @param newCount the count value to add to the monitored count
  9935. * @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.
  9936. */
  9937. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  9938. if (!PerfCounter.Enabled) {
  9939. return;
  9940. }
  9941. this._current += newCount;
  9942. if (fetchResult) {
  9943. this._fetchResult();
  9944. }
  9945. };
  9946. /**
  9947. * Start monitoring this performance counter
  9948. */
  9949. PerfCounter.prototype.beginMonitoring = function () {
  9950. if (!PerfCounter.Enabled) {
  9951. return;
  9952. }
  9953. this._startMonitoringTime = Tools.Now;
  9954. };
  9955. /**
  9956. * Compute the time lapsed since the previous beginMonitoring() call.
  9957. * @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
  9958. */
  9959. PerfCounter.prototype.endMonitoring = function (newFrame) {
  9960. if (newFrame === void 0) { newFrame = true; }
  9961. if (!PerfCounter.Enabled) {
  9962. return;
  9963. }
  9964. if (newFrame) {
  9965. this.fetchNewFrame();
  9966. }
  9967. var currentTime = Tools.Now;
  9968. this._current = currentTime - this._startMonitoringTime;
  9969. if (newFrame) {
  9970. this._fetchResult();
  9971. }
  9972. };
  9973. PerfCounter.prototype._fetchResult = function () {
  9974. this._totalAccumulated += this._current;
  9975. this._lastSecAccumulated += this._current;
  9976. // Min/Max update
  9977. this._min = Math.min(this._min, this._current);
  9978. this._max = Math.max(this._max, this._current);
  9979. this._average = this._totalAccumulated / this._totalValueCount;
  9980. // Reset last sec?
  9981. var now = Tools.Now;
  9982. if ((now - this._lastSecTime) > 1000) {
  9983. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  9984. this._lastSecTime = now;
  9985. this._lastSecAccumulated = 0;
  9986. this._lastSecValueCount = 0;
  9987. }
  9988. };
  9989. PerfCounter.Enabled = true;
  9990. return PerfCounter;
  9991. }());
  9992. BABYLON.PerfCounter = PerfCounter;
  9993. /**
  9994. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  9995. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  9996. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  9997. * @param name The name of the class, case should be preserved
  9998. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  9999. */
  10000. function className(name, module) {
  10001. return function (target) {
  10002. target["__bjsclassName__"] = name;
  10003. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10004. };
  10005. }
  10006. BABYLON.className = className;
  10007. /**
  10008. * An implementation of a loop for asynchronous functions.
  10009. */
  10010. var AsyncLoop = /** @class */ (function () {
  10011. /**
  10012. * Constroctor.
  10013. * @param iterations the number of iterations.
  10014. * @param _fn the function to run each iteration
  10015. * @param _successCallback the callback that will be called upon succesful execution
  10016. * @param offset starting offset.
  10017. */
  10018. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  10019. if (offset === void 0) { offset = 0; }
  10020. this.iterations = iterations;
  10021. this._fn = _fn;
  10022. this._successCallback = _successCallback;
  10023. this.index = offset - 1;
  10024. this._done = false;
  10025. }
  10026. /**
  10027. * Execute the next iteration. Must be called after the last iteration was finished.
  10028. */
  10029. AsyncLoop.prototype.executeNext = function () {
  10030. if (!this._done) {
  10031. if (this.index + 1 < this.iterations) {
  10032. ++this.index;
  10033. this._fn(this);
  10034. }
  10035. else {
  10036. this.breakLoop();
  10037. }
  10038. }
  10039. };
  10040. /**
  10041. * Break the loop and run the success callback.
  10042. */
  10043. AsyncLoop.prototype.breakLoop = function () {
  10044. this._done = true;
  10045. this._successCallback();
  10046. };
  10047. /**
  10048. * Helper function
  10049. */
  10050. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10051. if (offset === void 0) { offset = 0; }
  10052. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10053. loop.executeNext();
  10054. return loop;
  10055. };
  10056. /**
  10057. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10058. * @param iterations total number of iterations
  10059. * @param syncedIterations number of synchronous iterations in each async iteration.
  10060. * @param fn the function to call each iteration.
  10061. * @param callback a success call back that will be called when iterating stops.
  10062. * @param breakFunction a break condition (optional)
  10063. * @param timeout timeout settings for the setTimeout function. default - 0.
  10064. * @constructor
  10065. */
  10066. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10067. if (timeout === void 0) { timeout = 0; }
  10068. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10069. if (breakFunction && breakFunction())
  10070. loop.breakLoop();
  10071. else {
  10072. setTimeout(function () {
  10073. for (var i = 0; i < syncedIterations; ++i) {
  10074. var iteration = (loop.index * syncedIterations) + i;
  10075. if (iteration >= iterations)
  10076. break;
  10077. fn(iteration);
  10078. if (breakFunction && breakFunction()) {
  10079. loop.breakLoop();
  10080. break;
  10081. }
  10082. }
  10083. loop.executeNext();
  10084. }, timeout);
  10085. }
  10086. }, callback);
  10087. };
  10088. return AsyncLoop;
  10089. }());
  10090. BABYLON.AsyncLoop = AsyncLoop;
  10091. })(BABYLON || (BABYLON = {}));
  10092. //# sourceMappingURL=babylon.tools.js.map
  10093. var BABYLON;
  10094. (function (BABYLON) {
  10095. var PromiseStates;
  10096. (function (PromiseStates) {
  10097. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10098. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10099. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10100. })(PromiseStates || (PromiseStates = {}));
  10101. var FulFillmentAgregator = /** @class */ (function () {
  10102. function FulFillmentAgregator() {
  10103. this.count = 0;
  10104. this.target = 0;
  10105. this.results = [];
  10106. }
  10107. return FulFillmentAgregator;
  10108. }());
  10109. var InternalPromise = /** @class */ (function () {
  10110. function InternalPromise(resolver) {
  10111. var _this = this;
  10112. this._state = PromiseStates.Pending;
  10113. this._children = new Array();
  10114. this._rejectWasConsumed = false;
  10115. if (!resolver) {
  10116. return;
  10117. }
  10118. try {
  10119. resolver(function (value) {
  10120. _this._resolve(value);
  10121. }, function (reason) {
  10122. _this._reject(reason);
  10123. });
  10124. }
  10125. catch (e) {
  10126. this._reject(e);
  10127. }
  10128. }
  10129. Object.defineProperty(InternalPromise.prototype, "_result", {
  10130. get: function () {
  10131. return this._resultValue;
  10132. },
  10133. set: function (value) {
  10134. this._resultValue = value;
  10135. if (this._parent && this._parent._result === undefined) {
  10136. this._parent._result = value;
  10137. }
  10138. },
  10139. enumerable: true,
  10140. configurable: true
  10141. });
  10142. InternalPromise.prototype.catch = function (onRejected) {
  10143. return this.then(undefined, onRejected);
  10144. };
  10145. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10146. var _this = this;
  10147. var newPromise = new InternalPromise();
  10148. newPromise._onFulfilled = onFulfilled;
  10149. newPromise._onRejected = onRejected;
  10150. // Composition
  10151. this._children.push(newPromise);
  10152. newPromise._parent = this;
  10153. if (this._state !== PromiseStates.Pending) {
  10154. BABYLON.Tools.SetImmediate(function () {
  10155. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10156. var returnedValue = newPromise._resolve(_this._result);
  10157. if (returnedValue !== undefined && returnedValue !== null) {
  10158. if (returnedValue._state !== undefined) {
  10159. var returnedPromise = returnedValue;
  10160. newPromise._children.push(returnedPromise);
  10161. returnedPromise._parent = newPromise;
  10162. newPromise = returnedPromise;
  10163. }
  10164. else {
  10165. newPromise._result = returnedValue;
  10166. }
  10167. }
  10168. }
  10169. else {
  10170. newPromise._reject(_this._reason);
  10171. }
  10172. });
  10173. }
  10174. return newPromise;
  10175. };
  10176. InternalPromise.prototype._moveChildren = function (children) {
  10177. var _this = this;
  10178. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10179. this._children.forEach(function (child) {
  10180. child._parent = _this;
  10181. });
  10182. if (this._state === PromiseStates.Fulfilled) {
  10183. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10184. var child = _b[_i];
  10185. child._resolve(this._result);
  10186. }
  10187. }
  10188. else if (this._state === PromiseStates.Rejected) {
  10189. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10190. var child = _d[_c];
  10191. child._reject(this._reason);
  10192. }
  10193. }
  10194. var _a;
  10195. };
  10196. InternalPromise.prototype._resolve = function (value) {
  10197. try {
  10198. this._state = PromiseStates.Fulfilled;
  10199. var returnedValue = null;
  10200. if (this._onFulfilled) {
  10201. returnedValue = this._onFulfilled(value);
  10202. }
  10203. if (returnedValue !== undefined && returnedValue !== null) {
  10204. if (returnedValue._state !== undefined) {
  10205. // Transmit children
  10206. var returnedPromise = returnedValue;
  10207. returnedPromise._parent = this;
  10208. returnedPromise._moveChildren(this._children);
  10209. value = returnedPromise._result;
  10210. }
  10211. else {
  10212. value = returnedValue;
  10213. }
  10214. }
  10215. this._result = value;
  10216. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10217. var child = _a[_i];
  10218. child._resolve(value);
  10219. }
  10220. this._children.length = 0;
  10221. delete this._onFulfilled;
  10222. delete this._onRejected;
  10223. }
  10224. catch (e) {
  10225. this._reject(e, true);
  10226. }
  10227. };
  10228. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10229. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10230. this._state = PromiseStates.Rejected;
  10231. this._reason = reason;
  10232. if (this._onRejected && !onLocalThrow) {
  10233. try {
  10234. this._onRejected(reason);
  10235. this._rejectWasConsumed = true;
  10236. }
  10237. catch (e) {
  10238. reason = e;
  10239. }
  10240. }
  10241. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10242. var child = _a[_i];
  10243. if (this._rejectWasConsumed) {
  10244. child._resolve(null);
  10245. }
  10246. else {
  10247. child._reject(reason);
  10248. }
  10249. }
  10250. this._children.length = 0;
  10251. delete this._onFulfilled;
  10252. delete this._onRejected;
  10253. };
  10254. InternalPromise.resolve = function (value) {
  10255. var newPromise = new InternalPromise();
  10256. newPromise._resolve(value);
  10257. return newPromise;
  10258. };
  10259. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10260. promise.then(function (value) {
  10261. agregator.results[index] = value;
  10262. agregator.count++;
  10263. if (agregator.count === agregator.target) {
  10264. agregator.rootPromise._resolve(agregator.results);
  10265. }
  10266. return null;
  10267. }, function (reason) {
  10268. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10269. agregator.rootPromise._reject(reason);
  10270. }
  10271. });
  10272. };
  10273. InternalPromise.all = function (promises) {
  10274. var newPromise = new InternalPromise();
  10275. var agregator = new FulFillmentAgregator();
  10276. agregator.target = promises.length;
  10277. agregator.rootPromise = newPromise;
  10278. if (promises.length) {
  10279. for (var index = 0; index < promises.length; index++) {
  10280. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10281. }
  10282. }
  10283. else {
  10284. newPromise._resolve([]);
  10285. }
  10286. return newPromise;
  10287. };
  10288. InternalPromise.race = function (promises) {
  10289. var newPromise = new InternalPromise();
  10290. if (promises.length) {
  10291. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10292. var promise = promises_1[_i];
  10293. promise.then(function (value) {
  10294. if (newPromise) {
  10295. newPromise._resolve(value);
  10296. newPromise = null;
  10297. }
  10298. return null;
  10299. }, function (reason) {
  10300. if (newPromise) {
  10301. newPromise._reject(reason);
  10302. newPromise = null;
  10303. }
  10304. });
  10305. }
  10306. }
  10307. return newPromise;
  10308. };
  10309. return InternalPromise;
  10310. }());
  10311. /**
  10312. * Helper class that provides a small promise polyfill
  10313. */
  10314. var PromisePolyfill = /** @class */ (function () {
  10315. function PromisePolyfill() {
  10316. }
  10317. /**
  10318. * Static function used to check if the polyfill is required
  10319. * If this is the case then the function will inject the polyfill to window.Promise
  10320. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10321. */
  10322. PromisePolyfill.Apply = function (force) {
  10323. if (force === void 0) { force = false; }
  10324. if (force || typeof Promise === 'undefined') {
  10325. var root = window;
  10326. root.Promise = InternalPromise;
  10327. }
  10328. };
  10329. return PromisePolyfill;
  10330. }());
  10331. BABYLON.PromisePolyfill = PromisePolyfill;
  10332. })(BABYLON || (BABYLON = {}));
  10333. //# sourceMappingURL=babylon.promise.js.map
  10334. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10335. var BABYLON;
  10336. (function (BABYLON) {
  10337. /**
  10338. * Helper class to push actions to a pool of workers.
  10339. */
  10340. var WorkerPool = /** @class */ (function () {
  10341. /**
  10342. * Constructor
  10343. * @param workers Array of workers to use for actions
  10344. */
  10345. function WorkerPool(workers) {
  10346. this._pendingActions = new Array();
  10347. this._workerInfos = workers.map(function (worker) { return ({
  10348. worker: worker,
  10349. active: false
  10350. }); });
  10351. }
  10352. /**
  10353. * Terminates all workers and clears any pending actions.
  10354. */
  10355. WorkerPool.prototype.dispose = function () {
  10356. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10357. var workerInfo = _a[_i];
  10358. workerInfo.worker.terminate();
  10359. }
  10360. delete this._workerInfos;
  10361. delete this._pendingActions;
  10362. };
  10363. /**
  10364. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10365. * pended until a worker has completed its action.
  10366. * @param action The action to perform. Call onComplete when the action is complete.
  10367. */
  10368. WorkerPool.prototype.push = function (action) {
  10369. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10370. var workerInfo = _a[_i];
  10371. if (!workerInfo.active) {
  10372. this._execute(workerInfo, action);
  10373. return;
  10374. }
  10375. }
  10376. this._pendingActions.push(action);
  10377. };
  10378. WorkerPool.prototype._execute = function (workerInfo, action) {
  10379. var _this = this;
  10380. workerInfo.active = true;
  10381. action(workerInfo.worker, function () {
  10382. workerInfo.active = false;
  10383. var nextAction = _this._pendingActions.shift();
  10384. if (nextAction) {
  10385. _this._execute(workerInfo, nextAction);
  10386. }
  10387. });
  10388. };
  10389. return WorkerPool;
  10390. }());
  10391. BABYLON.WorkerPool = WorkerPool;
  10392. })(BABYLON || (BABYLON = {}));
  10393. //# sourceMappingURL=babylon.workerPool.js.map
  10394. var BABYLON;
  10395. (function (BABYLON) {
  10396. /**
  10397. * @hidden
  10398. **/
  10399. var _AlphaState = /** @class */ (function () {
  10400. /**
  10401. * Initializes the state.
  10402. */
  10403. function _AlphaState() {
  10404. this._isAlphaBlendDirty = false;
  10405. this._isBlendFunctionParametersDirty = false;
  10406. this._isBlendEquationParametersDirty = false;
  10407. this._isBlendConstantsDirty = false;
  10408. this._alphaBlend = false;
  10409. this._blendFunctionParameters = new Array(4);
  10410. this._blendEquationParameters = new Array(2);
  10411. this._blendConstants = new Array(4);
  10412. this.reset();
  10413. }
  10414. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10415. get: function () {
  10416. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10417. },
  10418. enumerable: true,
  10419. configurable: true
  10420. });
  10421. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10422. get: function () {
  10423. return this._alphaBlend;
  10424. },
  10425. set: function (value) {
  10426. if (this._alphaBlend === value) {
  10427. return;
  10428. }
  10429. this._alphaBlend = value;
  10430. this._isAlphaBlendDirty = true;
  10431. },
  10432. enumerable: true,
  10433. configurable: true
  10434. });
  10435. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10436. if (this._blendConstants[0] === r &&
  10437. this._blendConstants[1] === g &&
  10438. this._blendConstants[2] === b &&
  10439. this._blendConstants[3] === a) {
  10440. return;
  10441. }
  10442. this._blendConstants[0] = r;
  10443. this._blendConstants[1] = g;
  10444. this._blendConstants[2] = b;
  10445. this._blendConstants[3] = a;
  10446. this._isBlendConstantsDirty = true;
  10447. };
  10448. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10449. if (this._blendFunctionParameters[0] === value0 &&
  10450. this._blendFunctionParameters[1] === value1 &&
  10451. this._blendFunctionParameters[2] === value2 &&
  10452. this._blendFunctionParameters[3] === value3) {
  10453. return;
  10454. }
  10455. this._blendFunctionParameters[0] = value0;
  10456. this._blendFunctionParameters[1] = value1;
  10457. this._blendFunctionParameters[2] = value2;
  10458. this._blendFunctionParameters[3] = value3;
  10459. this._isBlendFunctionParametersDirty = true;
  10460. };
  10461. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10462. if (this._blendEquationParameters[0] === rgb &&
  10463. this._blendEquationParameters[1] === alpha) {
  10464. return;
  10465. }
  10466. this._blendEquationParameters[0] = rgb;
  10467. this._blendEquationParameters[1] = alpha;
  10468. this._isBlendEquationParametersDirty = true;
  10469. };
  10470. _AlphaState.prototype.reset = function () {
  10471. this._alphaBlend = false;
  10472. this._blendFunctionParameters[0] = null;
  10473. this._blendFunctionParameters[1] = null;
  10474. this._blendFunctionParameters[2] = null;
  10475. this._blendFunctionParameters[3] = null;
  10476. this._blendEquationParameters[0] = null;
  10477. this._blendEquationParameters[1] = null;
  10478. this._blendConstants[0] = null;
  10479. this._blendConstants[1] = null;
  10480. this._blendConstants[2] = null;
  10481. this._blendConstants[3] = null;
  10482. this._isAlphaBlendDirty = true;
  10483. this._isBlendFunctionParametersDirty = false;
  10484. this._isBlendEquationParametersDirty = false;
  10485. this._isBlendConstantsDirty = false;
  10486. };
  10487. _AlphaState.prototype.apply = function (gl) {
  10488. if (!this.isDirty) {
  10489. return;
  10490. }
  10491. // Alpha blend
  10492. if (this._isAlphaBlendDirty) {
  10493. if (this._alphaBlend) {
  10494. gl.enable(gl.BLEND);
  10495. }
  10496. else {
  10497. gl.disable(gl.BLEND);
  10498. }
  10499. this._isAlphaBlendDirty = false;
  10500. }
  10501. // Alpha function
  10502. if (this._isBlendFunctionParametersDirty) {
  10503. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10504. this._isBlendFunctionParametersDirty = false;
  10505. }
  10506. // Alpha equation
  10507. if (this._isBlendEquationParametersDirty) {
  10508. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10509. this._isBlendEquationParametersDirty = false;
  10510. }
  10511. // Constants
  10512. if (this._isBlendConstantsDirty) {
  10513. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10514. this._isBlendConstantsDirty = false;
  10515. }
  10516. };
  10517. return _AlphaState;
  10518. }());
  10519. BABYLON._AlphaState = _AlphaState;
  10520. })(BABYLON || (BABYLON = {}));
  10521. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10522. var BABYLON;
  10523. (function (BABYLON) {
  10524. /**
  10525. * @hidden
  10526. **/
  10527. var _DepthCullingState = /** @class */ (function () {
  10528. /**
  10529. * Initializes the state.
  10530. */
  10531. function _DepthCullingState() {
  10532. this._isDepthTestDirty = false;
  10533. this._isDepthMaskDirty = false;
  10534. this._isDepthFuncDirty = false;
  10535. this._isCullFaceDirty = false;
  10536. this._isCullDirty = false;
  10537. this._isZOffsetDirty = false;
  10538. this._isFrontFaceDirty = false;
  10539. this.reset();
  10540. }
  10541. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10542. get: function () {
  10543. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10544. },
  10545. enumerable: true,
  10546. configurable: true
  10547. });
  10548. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10549. get: function () {
  10550. return this._zOffset;
  10551. },
  10552. set: function (value) {
  10553. if (this._zOffset === value) {
  10554. return;
  10555. }
  10556. this._zOffset = value;
  10557. this._isZOffsetDirty = true;
  10558. },
  10559. enumerable: true,
  10560. configurable: true
  10561. });
  10562. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10563. get: function () {
  10564. return this._cullFace;
  10565. },
  10566. set: function (value) {
  10567. if (this._cullFace === value) {
  10568. return;
  10569. }
  10570. this._cullFace = value;
  10571. this._isCullFaceDirty = true;
  10572. },
  10573. enumerable: true,
  10574. configurable: true
  10575. });
  10576. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10577. get: function () {
  10578. return this._cull;
  10579. },
  10580. set: function (value) {
  10581. if (this._cull === value) {
  10582. return;
  10583. }
  10584. this._cull = value;
  10585. this._isCullDirty = true;
  10586. },
  10587. enumerable: true,
  10588. configurable: true
  10589. });
  10590. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10591. get: function () {
  10592. return this._depthFunc;
  10593. },
  10594. set: function (value) {
  10595. if (this._depthFunc === value) {
  10596. return;
  10597. }
  10598. this._depthFunc = value;
  10599. this._isDepthFuncDirty = true;
  10600. },
  10601. enumerable: true,
  10602. configurable: true
  10603. });
  10604. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10605. get: function () {
  10606. return this._depthMask;
  10607. },
  10608. set: function (value) {
  10609. if (this._depthMask === value) {
  10610. return;
  10611. }
  10612. this._depthMask = value;
  10613. this._isDepthMaskDirty = true;
  10614. },
  10615. enumerable: true,
  10616. configurable: true
  10617. });
  10618. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10619. get: function () {
  10620. return this._depthTest;
  10621. },
  10622. set: function (value) {
  10623. if (this._depthTest === value) {
  10624. return;
  10625. }
  10626. this._depthTest = value;
  10627. this._isDepthTestDirty = true;
  10628. },
  10629. enumerable: true,
  10630. configurable: true
  10631. });
  10632. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10633. get: function () {
  10634. return this._frontFace;
  10635. },
  10636. set: function (value) {
  10637. if (this._frontFace === value) {
  10638. return;
  10639. }
  10640. this._frontFace = value;
  10641. this._isFrontFaceDirty = true;
  10642. },
  10643. enumerable: true,
  10644. configurable: true
  10645. });
  10646. _DepthCullingState.prototype.reset = function () {
  10647. this._depthMask = true;
  10648. this._depthTest = true;
  10649. this._depthFunc = null;
  10650. this._cullFace = null;
  10651. this._cull = null;
  10652. this._zOffset = 0;
  10653. this._frontFace = null;
  10654. this._isDepthTestDirty = true;
  10655. this._isDepthMaskDirty = true;
  10656. this._isDepthFuncDirty = false;
  10657. this._isCullFaceDirty = false;
  10658. this._isCullDirty = false;
  10659. this._isZOffsetDirty = false;
  10660. this._isFrontFaceDirty = false;
  10661. };
  10662. _DepthCullingState.prototype.apply = function (gl) {
  10663. if (!this.isDirty) {
  10664. return;
  10665. }
  10666. // Cull
  10667. if (this._isCullDirty) {
  10668. if (this.cull) {
  10669. gl.enable(gl.CULL_FACE);
  10670. }
  10671. else {
  10672. gl.disable(gl.CULL_FACE);
  10673. }
  10674. this._isCullDirty = false;
  10675. }
  10676. // Cull face
  10677. if (this._isCullFaceDirty) {
  10678. gl.cullFace(this.cullFace);
  10679. this._isCullFaceDirty = false;
  10680. }
  10681. // Depth mask
  10682. if (this._isDepthMaskDirty) {
  10683. gl.depthMask(this.depthMask);
  10684. this._isDepthMaskDirty = false;
  10685. }
  10686. // Depth test
  10687. if (this._isDepthTestDirty) {
  10688. if (this.depthTest) {
  10689. gl.enable(gl.DEPTH_TEST);
  10690. }
  10691. else {
  10692. gl.disable(gl.DEPTH_TEST);
  10693. }
  10694. this._isDepthTestDirty = false;
  10695. }
  10696. // Depth func
  10697. if (this._isDepthFuncDirty) {
  10698. gl.depthFunc(this.depthFunc);
  10699. this._isDepthFuncDirty = false;
  10700. }
  10701. // zOffset
  10702. if (this._isZOffsetDirty) {
  10703. if (this.zOffset) {
  10704. gl.enable(gl.POLYGON_OFFSET_FILL);
  10705. gl.polygonOffset(this.zOffset, 0);
  10706. }
  10707. else {
  10708. gl.disable(gl.POLYGON_OFFSET_FILL);
  10709. }
  10710. this._isZOffsetDirty = false;
  10711. }
  10712. // Front face
  10713. if (this._isFrontFaceDirty) {
  10714. gl.frontFace(this.frontFace);
  10715. this._isFrontFaceDirty = false;
  10716. }
  10717. };
  10718. return _DepthCullingState;
  10719. }());
  10720. BABYLON._DepthCullingState = _DepthCullingState;
  10721. })(BABYLON || (BABYLON = {}));
  10722. //# sourceMappingURL=babylon.depthCullingState.js.map
  10723. var BABYLON;
  10724. (function (BABYLON) {
  10725. /**
  10726. * @hidden
  10727. **/
  10728. var _StencilState = /** @class */ (function () {
  10729. function _StencilState() {
  10730. this._isStencilTestDirty = false;
  10731. this._isStencilMaskDirty = false;
  10732. this._isStencilFuncDirty = false;
  10733. this._isStencilOpDirty = false;
  10734. this.reset();
  10735. }
  10736. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10737. get: function () {
  10738. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10739. },
  10740. enumerable: true,
  10741. configurable: true
  10742. });
  10743. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10744. get: function () {
  10745. return this._stencilFunc;
  10746. },
  10747. set: function (value) {
  10748. if (this._stencilFunc === value) {
  10749. return;
  10750. }
  10751. this._stencilFunc = value;
  10752. this._isStencilFuncDirty = true;
  10753. },
  10754. enumerable: true,
  10755. configurable: true
  10756. });
  10757. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10758. get: function () {
  10759. return this._stencilFuncRef;
  10760. },
  10761. set: function (value) {
  10762. if (this._stencilFuncRef === value) {
  10763. return;
  10764. }
  10765. this._stencilFuncRef = value;
  10766. this._isStencilFuncDirty = true;
  10767. },
  10768. enumerable: true,
  10769. configurable: true
  10770. });
  10771. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10772. get: function () {
  10773. return this._stencilFuncMask;
  10774. },
  10775. set: function (value) {
  10776. if (this._stencilFuncMask === value) {
  10777. return;
  10778. }
  10779. this._stencilFuncMask = value;
  10780. this._isStencilFuncDirty = true;
  10781. },
  10782. enumerable: true,
  10783. configurable: true
  10784. });
  10785. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10786. get: function () {
  10787. return this._stencilOpStencilFail;
  10788. },
  10789. set: function (value) {
  10790. if (this._stencilOpStencilFail === value) {
  10791. return;
  10792. }
  10793. this._stencilOpStencilFail = value;
  10794. this._isStencilOpDirty = true;
  10795. },
  10796. enumerable: true,
  10797. configurable: true
  10798. });
  10799. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10800. get: function () {
  10801. return this._stencilOpDepthFail;
  10802. },
  10803. set: function (value) {
  10804. if (this._stencilOpDepthFail === value) {
  10805. return;
  10806. }
  10807. this._stencilOpDepthFail = value;
  10808. this._isStencilOpDirty = true;
  10809. },
  10810. enumerable: true,
  10811. configurable: true
  10812. });
  10813. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10814. get: function () {
  10815. return this._stencilOpStencilDepthPass;
  10816. },
  10817. set: function (value) {
  10818. if (this._stencilOpStencilDepthPass === value) {
  10819. return;
  10820. }
  10821. this._stencilOpStencilDepthPass = value;
  10822. this._isStencilOpDirty = true;
  10823. },
  10824. enumerable: true,
  10825. configurable: true
  10826. });
  10827. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10828. get: function () {
  10829. return this._stencilMask;
  10830. },
  10831. set: function (value) {
  10832. if (this._stencilMask === value) {
  10833. return;
  10834. }
  10835. this._stencilMask = value;
  10836. this._isStencilMaskDirty = true;
  10837. },
  10838. enumerable: true,
  10839. configurable: true
  10840. });
  10841. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10842. get: function () {
  10843. return this._stencilTest;
  10844. },
  10845. set: function (value) {
  10846. if (this._stencilTest === value) {
  10847. return;
  10848. }
  10849. this._stencilTest = value;
  10850. this._isStencilTestDirty = true;
  10851. },
  10852. enumerable: true,
  10853. configurable: true
  10854. });
  10855. _StencilState.prototype.reset = function () {
  10856. this._stencilTest = false;
  10857. this._stencilMask = 0xFF;
  10858. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10859. this._stencilFuncRef = 1;
  10860. this._stencilFuncMask = 0xFF;
  10861. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10862. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10863. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10864. this._isStencilTestDirty = true;
  10865. this._isStencilMaskDirty = true;
  10866. this._isStencilFuncDirty = true;
  10867. this._isStencilOpDirty = true;
  10868. };
  10869. _StencilState.prototype.apply = function (gl) {
  10870. if (!this.isDirty) {
  10871. return;
  10872. }
  10873. // Stencil test
  10874. if (this._isStencilTestDirty) {
  10875. if (this.stencilTest) {
  10876. gl.enable(gl.STENCIL_TEST);
  10877. }
  10878. else {
  10879. gl.disable(gl.STENCIL_TEST);
  10880. }
  10881. this._isStencilTestDirty = false;
  10882. }
  10883. // Stencil mask
  10884. if (this._isStencilMaskDirty) {
  10885. gl.stencilMask(this.stencilMask);
  10886. this._isStencilMaskDirty = false;
  10887. }
  10888. // Stencil func
  10889. if (this._isStencilFuncDirty) {
  10890. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  10891. this._isStencilFuncDirty = false;
  10892. }
  10893. // Stencil op
  10894. if (this._isStencilOpDirty) {
  10895. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  10896. this._isStencilOpDirty = false;
  10897. }
  10898. };
  10899. return _StencilState;
  10900. }());
  10901. BABYLON._StencilState = _StencilState;
  10902. })(BABYLON || (BABYLON = {}));
  10903. //# sourceMappingURL=babylon.stencilState.js.map
  10904. var __assign = (this && this.__assign) || Object.assign || function(t) {
  10905. for (var s, i = 1, n = arguments.length; i < n; i++) {
  10906. s = arguments[i];
  10907. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  10908. t[p] = s[p];
  10909. }
  10910. return t;
  10911. };
  10912. var BABYLON;
  10913. (function (BABYLON) {
  10914. var compileShader = function (gl, source, type, defines, shaderVersion) {
  10915. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  10916. };
  10917. var compileRawShader = function (gl, source, type) {
  10918. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  10919. gl.shaderSource(shader, source);
  10920. gl.compileShader(shader);
  10921. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  10922. var log = gl.getShaderInfoLog(shader);
  10923. if (log) {
  10924. throw new Error(log);
  10925. }
  10926. }
  10927. if (!shader) {
  10928. throw new Error("Something went wrong while compile the shader.");
  10929. }
  10930. return shader;
  10931. };
  10932. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  10933. var magFilter = gl.NEAREST;
  10934. var minFilter = gl.NEAREST;
  10935. switch (samplingMode) {
  10936. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  10937. magFilter = gl.LINEAR;
  10938. if (generateMipMaps) {
  10939. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10940. }
  10941. else {
  10942. minFilter = gl.LINEAR;
  10943. }
  10944. break;
  10945. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  10946. magFilter = gl.LINEAR;
  10947. if (generateMipMaps) {
  10948. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10949. }
  10950. else {
  10951. minFilter = gl.LINEAR;
  10952. }
  10953. break;
  10954. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  10955. magFilter = gl.NEAREST;
  10956. if (generateMipMaps) {
  10957. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  10958. }
  10959. else {
  10960. minFilter = gl.NEAREST;
  10961. }
  10962. break;
  10963. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  10964. magFilter = gl.NEAREST;
  10965. if (generateMipMaps) {
  10966. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  10967. }
  10968. else {
  10969. minFilter = gl.NEAREST;
  10970. }
  10971. break;
  10972. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  10973. magFilter = gl.NEAREST;
  10974. if (generateMipMaps) {
  10975. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  10976. }
  10977. else {
  10978. minFilter = gl.LINEAR;
  10979. }
  10980. break;
  10981. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  10982. magFilter = gl.NEAREST;
  10983. if (generateMipMaps) {
  10984. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  10985. }
  10986. else {
  10987. minFilter = gl.LINEAR;
  10988. }
  10989. break;
  10990. case BABYLON.Texture.NEAREST_LINEAR:
  10991. magFilter = gl.NEAREST;
  10992. minFilter = gl.LINEAR;
  10993. break;
  10994. case BABYLON.Texture.NEAREST_NEAREST:
  10995. magFilter = gl.NEAREST;
  10996. minFilter = gl.NEAREST;
  10997. break;
  10998. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  10999. magFilter = gl.LINEAR;
  11000. if (generateMipMaps) {
  11001. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11002. }
  11003. else {
  11004. minFilter = gl.NEAREST;
  11005. }
  11006. break;
  11007. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  11008. magFilter = gl.LINEAR;
  11009. if (generateMipMaps) {
  11010. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11011. }
  11012. else {
  11013. minFilter = gl.NEAREST;
  11014. }
  11015. break;
  11016. case BABYLON.Texture.LINEAR_LINEAR:
  11017. magFilter = gl.LINEAR;
  11018. minFilter = gl.LINEAR;
  11019. break;
  11020. case BABYLON.Texture.LINEAR_NEAREST:
  11021. magFilter = gl.LINEAR;
  11022. minFilter = gl.NEAREST;
  11023. break;
  11024. }
  11025. return {
  11026. min: minFilter,
  11027. mag: magFilter
  11028. };
  11029. };
  11030. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  11031. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  11032. var img;
  11033. var onload = function () {
  11034. loadedImages[index] = img;
  11035. loadedImages._internalCount++;
  11036. if (scene) {
  11037. scene._removePendingData(img);
  11038. }
  11039. if (loadedImages._internalCount === 6) {
  11040. onfinish(loadedImages);
  11041. }
  11042. };
  11043. var onerror = function (message, exception) {
  11044. if (scene) {
  11045. scene._removePendingData(img);
  11046. }
  11047. if (onErrorCallBack) {
  11048. onErrorCallBack(message, exception);
  11049. }
  11050. };
  11051. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  11052. if (scene) {
  11053. scene._addPendingData(img);
  11054. }
  11055. };
  11056. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  11057. if (onError === void 0) { onError = null; }
  11058. var loadedImages = [];
  11059. loadedImages._internalCount = 0;
  11060. for (var index = 0; index < 6; index++) {
  11061. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  11062. }
  11063. };
  11064. var BufferPointer = /** @class */ (function () {
  11065. function BufferPointer() {
  11066. }
  11067. return BufferPointer;
  11068. }());
  11069. /**
  11070. * Interface for attribute information associated with buffer instanciation
  11071. */
  11072. var InstancingAttributeInfo = /** @class */ (function () {
  11073. function InstancingAttributeInfo() {
  11074. }
  11075. return InstancingAttributeInfo;
  11076. }());
  11077. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11078. /**
  11079. * Define options used to create a render target texture
  11080. */
  11081. var RenderTargetCreationOptions = /** @class */ (function () {
  11082. function RenderTargetCreationOptions() {
  11083. }
  11084. return RenderTargetCreationOptions;
  11085. }());
  11086. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11087. /**
  11088. * Define options used to create a depth texture
  11089. */
  11090. var DepthTextureCreationOptions = /** @class */ (function () {
  11091. function DepthTextureCreationOptions() {
  11092. }
  11093. return DepthTextureCreationOptions;
  11094. }());
  11095. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11096. /**
  11097. * Class used to describe the capabilities of the engine relatively to the current browser
  11098. */
  11099. var EngineCapabilities = /** @class */ (function () {
  11100. function EngineCapabilities() {
  11101. }
  11102. return EngineCapabilities;
  11103. }());
  11104. BABYLON.EngineCapabilities = EngineCapabilities;
  11105. /**
  11106. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11107. */
  11108. var Engine = /** @class */ (function () {
  11109. /**
  11110. * Creates a new engine
  11111. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  11112. * @param antialias defines enable antialiasing (default: false)
  11113. * @param options defines further options to be sent to the getContext() function
  11114. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11115. */
  11116. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11117. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11118. var _this = this;
  11119. // Public members
  11120. /**
  11121. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11122. */
  11123. this.forcePOTTextures = false;
  11124. /**
  11125. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11126. */
  11127. this.isFullscreen = false;
  11128. /**
  11129. * Gets a boolean indicating if the pointer is currently locked
  11130. */
  11131. this.isPointerLock = false;
  11132. /**
  11133. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11134. */
  11135. this.cullBackFaces = true;
  11136. /**
  11137. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11138. */
  11139. this.renderEvenInBackground = true;
  11140. /**
  11141. * Gets or sets a boolean indicating that cache can be kept between frames
  11142. */
  11143. this.preventCacheWipeBetweenFrames = false;
  11144. /**
  11145. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11146. **/
  11147. this.enableOfflineSupport = false;
  11148. /**
  11149. * 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)
  11150. **/
  11151. this.disableManifestCheck = false;
  11152. /**
  11153. * Gets the list of created scenes
  11154. */
  11155. this.scenes = new Array();
  11156. /**
  11157. * Gets the list of created postprocesses
  11158. */
  11159. this.postProcesses = new Array();
  11160. // Observables
  11161. /**
  11162. * Observable event triggered each time the rendering canvas is resized
  11163. */
  11164. this.onResizeObservable = new BABYLON.Observable();
  11165. /**
  11166. * Observable event triggered each time the canvas loses focus
  11167. */
  11168. this.onCanvasBlurObservable = new BABYLON.Observable();
  11169. /**
  11170. * Observable event triggered each time the canvas gains focus
  11171. */
  11172. this.onCanvasFocusObservable = new BABYLON.Observable();
  11173. /**
  11174. * Observable event triggered each time the canvas receives pointerout event
  11175. */
  11176. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11177. /**
  11178. * Observable event triggered before each texture is initialized
  11179. */
  11180. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11181. //WebVR
  11182. this._vrDisplay = undefined;
  11183. this._vrSupported = false;
  11184. this._vrExclusivePointerMode = false;
  11185. // Uniform buffers list
  11186. /**
  11187. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11188. */
  11189. this.disableUniformBuffers = false;
  11190. /** @hidden */
  11191. this._uniformBuffers = new Array();
  11192. // Observables
  11193. /**
  11194. * Observable raised when the engine begins a new frame
  11195. */
  11196. this.onBeginFrameObservable = new BABYLON.Observable();
  11197. /**
  11198. * Observable raised when the engine ends the current frame
  11199. */
  11200. this.onEndFrameObservable = new BABYLON.Observable();
  11201. /**
  11202. * Observable raised when the engine is about to compile a shader
  11203. */
  11204. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11205. /**
  11206. * Observable raised when the engine has jsut compiled a shader
  11207. */
  11208. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11209. this._windowIsBackground = false;
  11210. this._webGLVersion = 1.0;
  11211. /** @hidden */
  11212. this._badOS = false;
  11213. /** @hidden */
  11214. this._badDesktopOS = false;
  11215. /**
  11216. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11217. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11218. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11219. */
  11220. this.disableTextureBindingOptimization = false;
  11221. /**
  11222. * Observable signaled when VR display mode changes
  11223. */
  11224. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11225. /**
  11226. * Observable signaled when VR request present is complete
  11227. */
  11228. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11229. /**
  11230. * Observable signaled when VR request present starts
  11231. */
  11232. this.onVRRequestPresentStart = new BABYLON.Observable();
  11233. this._colorWrite = true;
  11234. /** @hidden */
  11235. this._drawCalls = new BABYLON.PerfCounter();
  11236. /** @hidden */
  11237. this._textureCollisions = new BABYLON.PerfCounter();
  11238. this._renderingQueueLaunched = false;
  11239. this._activeRenderLoops = new Array();
  11240. // Deterministic lockstepMaxSteps
  11241. this._deterministicLockstep = false;
  11242. this._lockstepMaxSteps = 4;
  11243. // Lost context
  11244. /**
  11245. * Observable signaled when a context lost event is raised
  11246. */
  11247. this.onContextLostObservable = new BABYLON.Observable();
  11248. /**
  11249. * Observable signaled when a context restored event is raised
  11250. */
  11251. this.onContextRestoredObservable = new BABYLON.Observable();
  11252. this._contextWasLost = false;
  11253. this._doNotHandleContextLost = false;
  11254. // FPS
  11255. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11256. this._fps = 60;
  11257. this._deltaTime = 0;
  11258. /**
  11259. * Turn this value on if you want to pause FPS computation when in background
  11260. */
  11261. this.disablePerformanceMonitorInBackground = false;
  11262. // States
  11263. /** @hidden */
  11264. this._depthCullingState = new BABYLON._DepthCullingState();
  11265. /** @hidden */
  11266. this._stencilState = new BABYLON._StencilState();
  11267. /** @hidden */
  11268. this._alphaState = new BABYLON._AlphaState();
  11269. /** @hidden */
  11270. this._alphaMode = Engine.ALPHA_DISABLE;
  11271. // Cache
  11272. this._internalTexturesCache = new Array();
  11273. /** @hidden */
  11274. this._activeChannel = 0;
  11275. this._currentTextureChannel = -1;
  11276. /** @hidden */
  11277. this._boundTexturesCache = {};
  11278. this._compiledEffects = {};
  11279. this._vertexAttribArraysEnabled = [];
  11280. this._uintIndicesCurrentlySet = false;
  11281. this._currentBoundBuffer = new Array();
  11282. this._currentBufferPointers = new Array();
  11283. this._currentInstanceLocations = new Array();
  11284. this._currentInstanceBuffers = new Array();
  11285. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11286. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11287. this._vaoRecordInProgress = false;
  11288. this._mustWipeVertexAttributes = false;
  11289. this._nextFreeTextureSlots = new Array();
  11290. this._maxSimultaneousTextures = 0;
  11291. this._activeRequests = new Array();
  11292. // Hardware supported Compressed Textures
  11293. this._texturesSupported = new Array();
  11294. this._onVRFullScreenTriggered = function () {
  11295. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11296. //get the old size before we change
  11297. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11298. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11299. //get the width and height, change the render size
  11300. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11301. _this.setHardwareScalingLevel(1);
  11302. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11303. }
  11304. else {
  11305. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11306. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11307. }
  11308. };
  11309. this._boundUniforms = {};
  11310. // Register promises
  11311. BABYLON.PromisePolyfill.Apply();
  11312. var canvas = null;
  11313. Engine.Instances.push(this);
  11314. if (!canvasOrContext) {
  11315. return;
  11316. }
  11317. options = options || {};
  11318. if (canvasOrContext.getContext) {
  11319. canvas = canvasOrContext;
  11320. this._renderingCanvas = canvas;
  11321. if (antialias != null) {
  11322. options.antialias = antialias;
  11323. }
  11324. if (options.deterministicLockstep === undefined) {
  11325. options.deterministicLockstep = false;
  11326. }
  11327. if (options.lockstepMaxSteps === undefined) {
  11328. options.lockstepMaxSteps = 4;
  11329. }
  11330. if (options.preserveDrawingBuffer === undefined) {
  11331. options.preserveDrawingBuffer = false;
  11332. }
  11333. if (options.audioEngine === undefined) {
  11334. options.audioEngine = true;
  11335. }
  11336. if (options.stencil === undefined) {
  11337. options.stencil = true;
  11338. }
  11339. this._deterministicLockstep = options.deterministicLockstep;
  11340. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11341. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11342. // Exceptions
  11343. if (navigator && navigator.userAgent) {
  11344. var ua = navigator.userAgent;
  11345. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11346. var exception = _a[_i];
  11347. var key = exception.key;
  11348. var targets = exception.targets;
  11349. if (ua.indexOf(key) > -1) {
  11350. if (exception.capture && exception.captureConstraint) {
  11351. var capture = exception.capture;
  11352. var constraint = exception.captureConstraint;
  11353. var regex = new RegExp(capture);
  11354. var matches = regex.exec(ua);
  11355. if (matches && matches.length > 0) {
  11356. var capturedValue = parseInt(matches[matches.length - 1]);
  11357. if (capturedValue >= constraint) {
  11358. continue;
  11359. }
  11360. }
  11361. }
  11362. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11363. var target = targets_1[_b];
  11364. switch (target) {
  11365. case "uniformBuffer":
  11366. this.disableUniformBuffers = true;
  11367. break;
  11368. case "textureBindingOptimization":
  11369. this.disableTextureBindingOptimization = true;
  11370. break;
  11371. }
  11372. }
  11373. }
  11374. }
  11375. }
  11376. // GL
  11377. if (!options.disableWebGL2Support) {
  11378. try {
  11379. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11380. if (this._gl) {
  11381. this._webGLVersion = 2.0;
  11382. }
  11383. }
  11384. catch (e) {
  11385. // Do nothing
  11386. }
  11387. }
  11388. if (!this._gl) {
  11389. if (!canvas) {
  11390. throw new Error("The provided canvas is null or undefined.");
  11391. }
  11392. try {
  11393. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11394. }
  11395. catch (e) {
  11396. throw new Error("WebGL not supported");
  11397. }
  11398. }
  11399. if (!this._gl) {
  11400. throw new Error("WebGL not supported");
  11401. }
  11402. this._onCanvasFocus = function () {
  11403. _this.onCanvasFocusObservable.notifyObservers(_this);
  11404. };
  11405. this._onCanvasBlur = function () {
  11406. _this.onCanvasBlurObservable.notifyObservers(_this);
  11407. };
  11408. canvas.addEventListener("focus", this._onCanvasFocus);
  11409. canvas.addEventListener("blur", this._onCanvasBlur);
  11410. this._onBlur = function () {
  11411. if (_this.disablePerformanceMonitorInBackground) {
  11412. _this._performanceMonitor.disable();
  11413. }
  11414. _this._windowIsBackground = true;
  11415. };
  11416. this._onFocus = function () {
  11417. if (_this.disablePerformanceMonitorInBackground) {
  11418. _this._performanceMonitor.enable();
  11419. }
  11420. _this._windowIsBackground = false;
  11421. };
  11422. this._onCanvasPointerOut = function (ev) {
  11423. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11424. };
  11425. window.addEventListener("blur", this._onBlur);
  11426. window.addEventListener("focus", this._onFocus);
  11427. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11428. // Context lost
  11429. if (!this._doNotHandleContextLost) {
  11430. this._onContextLost = function (evt) {
  11431. evt.preventDefault();
  11432. _this._contextWasLost = true;
  11433. BABYLON.Tools.Warn("WebGL context lost.");
  11434. _this.onContextLostObservable.notifyObservers(_this);
  11435. };
  11436. this._onContextRestored = function (evt) {
  11437. // Adding a timeout to avoid race condition at browser level
  11438. setTimeout(function () {
  11439. // Rebuild gl context
  11440. _this._initGLContext();
  11441. // Rebuild effects
  11442. _this._rebuildEffects();
  11443. // Rebuild textures
  11444. _this._rebuildInternalTextures();
  11445. // Rebuild buffers
  11446. _this._rebuildBuffers();
  11447. // Cache
  11448. _this.wipeCaches(true);
  11449. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11450. _this.onContextRestoredObservable.notifyObservers(_this);
  11451. _this._contextWasLost = false;
  11452. }, 0);
  11453. };
  11454. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11455. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11456. }
  11457. }
  11458. else {
  11459. this._gl = canvasOrContext;
  11460. this._renderingCanvas = this._gl.canvas;
  11461. if (this._gl.renderbufferStorageMultisample) {
  11462. this._webGLVersion = 2.0;
  11463. }
  11464. options.stencil = this._gl.getContextAttributes().stencil;
  11465. }
  11466. // Viewport
  11467. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11468. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11469. this.resize();
  11470. this._isStencilEnable = options.stencil ? true : false;
  11471. this._initGLContext();
  11472. if (canvas) {
  11473. // Fullscreen
  11474. this._onFullscreenChange = function () {
  11475. if (document.fullscreen !== undefined) {
  11476. _this.isFullscreen = document.fullscreen;
  11477. }
  11478. else if (document.mozFullScreen !== undefined) {
  11479. _this.isFullscreen = document.mozFullScreen;
  11480. }
  11481. else if (document.webkitIsFullScreen !== undefined) {
  11482. _this.isFullscreen = document.webkitIsFullScreen;
  11483. }
  11484. else if (document.msIsFullScreen !== undefined) {
  11485. _this.isFullscreen = document.msIsFullScreen;
  11486. }
  11487. // Pointer lock
  11488. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11489. canvas.requestPointerLock = canvas.requestPointerLock ||
  11490. canvas.msRequestPointerLock ||
  11491. canvas.mozRequestPointerLock ||
  11492. canvas.webkitRequestPointerLock;
  11493. if (canvas.requestPointerLock) {
  11494. canvas.requestPointerLock();
  11495. }
  11496. }
  11497. };
  11498. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11499. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11500. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11501. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11502. // Pointer lock
  11503. this._onPointerLockChange = function () {
  11504. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11505. document.webkitPointerLockElement === canvas ||
  11506. document.msPointerLockElement === canvas ||
  11507. document.pointerLockElement === canvas);
  11508. };
  11509. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11510. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11511. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11512. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11513. this._onVRDisplayPointerRestricted = function () {
  11514. if (canvas) {
  11515. canvas.requestPointerLock();
  11516. }
  11517. };
  11518. this._onVRDisplayPointerUnrestricted = function () {
  11519. document.exitPointerLock();
  11520. };
  11521. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11522. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11523. }
  11524. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11525. Engine.audioEngine = new BABYLON.AudioEngine();
  11526. }
  11527. // Prepare buffer pointers
  11528. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11529. this._currentBufferPointers[i] = new BufferPointer();
  11530. }
  11531. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11532. // Load WebVR Devices
  11533. if (options.autoEnableWebVR) {
  11534. this.initWebVR();
  11535. }
  11536. // Detect if we are running on a faulty buggy OS.
  11537. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11538. // Detect if we are running on a faulty buggy desktop OS.
  11539. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11540. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11541. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11542. }
  11543. Object.defineProperty(Engine, "LastCreatedEngine", {
  11544. /**
  11545. * Gets the latest created engine
  11546. */
  11547. get: function () {
  11548. if (Engine.Instances.length === 0) {
  11549. return null;
  11550. }
  11551. return Engine.Instances[Engine.Instances.length - 1];
  11552. },
  11553. enumerable: true,
  11554. configurable: true
  11555. });
  11556. Object.defineProperty(Engine, "LastCreatedScene", {
  11557. /**
  11558. * Gets the latest created scene
  11559. */
  11560. get: function () {
  11561. var lastCreatedEngine = Engine.LastCreatedEngine;
  11562. if (!lastCreatedEngine) {
  11563. return null;
  11564. }
  11565. if (lastCreatedEngine.scenes.length === 0) {
  11566. return null;
  11567. }
  11568. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11569. },
  11570. enumerable: true,
  11571. configurable: true
  11572. });
  11573. /**
  11574. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11575. * @param flag defines which part of the materials must be marked as dirty
  11576. * @param predicate defines a predicate used to filter which materials should be affected
  11577. */
  11578. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11579. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11580. var engine = Engine.Instances[engineIndex];
  11581. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11582. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11583. }
  11584. }
  11585. };
  11586. Object.defineProperty(Engine, "NEVER", {
  11587. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  11588. get: function () {
  11589. return Engine._NEVER;
  11590. },
  11591. enumerable: true,
  11592. configurable: true
  11593. });
  11594. Object.defineProperty(Engine, "ALWAYS", {
  11595. /** 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 */
  11596. get: function () {
  11597. return Engine._ALWAYS;
  11598. },
  11599. enumerable: true,
  11600. configurable: true
  11601. });
  11602. Object.defineProperty(Engine, "LESS", {
  11603. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  11604. get: function () {
  11605. return Engine._LESS;
  11606. },
  11607. enumerable: true,
  11608. configurable: true
  11609. });
  11610. Object.defineProperty(Engine, "EQUAL", {
  11611. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  11612. get: function () {
  11613. return Engine._EQUAL;
  11614. },
  11615. enumerable: true,
  11616. configurable: true
  11617. });
  11618. Object.defineProperty(Engine, "LEQUAL", {
  11619. /** 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 */
  11620. get: function () {
  11621. return Engine._LEQUAL;
  11622. },
  11623. enumerable: true,
  11624. configurable: true
  11625. });
  11626. Object.defineProperty(Engine, "GREATER", {
  11627. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  11628. get: function () {
  11629. return Engine._GREATER;
  11630. },
  11631. enumerable: true,
  11632. configurable: true
  11633. });
  11634. Object.defineProperty(Engine, "GEQUAL", {
  11635. /** 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 */
  11636. get: function () {
  11637. return Engine._GEQUAL;
  11638. },
  11639. enumerable: true,
  11640. configurable: true
  11641. });
  11642. Object.defineProperty(Engine, "NOTEQUAL", {
  11643. /** 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 */
  11644. get: function () {
  11645. return Engine._NOTEQUAL;
  11646. },
  11647. enumerable: true,
  11648. configurable: true
  11649. });
  11650. Object.defineProperty(Engine, "KEEP", {
  11651. /** Passed to stencilOperation to specify that stencil value must be kept */
  11652. get: function () {
  11653. return Engine._KEEP;
  11654. },
  11655. enumerable: true,
  11656. configurable: true
  11657. });
  11658. Object.defineProperty(Engine, "REPLACE", {
  11659. /** Passed to stencilOperation to specify that stencil value must be replaced */
  11660. get: function () {
  11661. return Engine._REPLACE;
  11662. },
  11663. enumerable: true,
  11664. configurable: true
  11665. });
  11666. Object.defineProperty(Engine, "INCR", {
  11667. /** Passed to stencilOperation to specify that stencil value must be incremented */
  11668. get: function () {
  11669. return Engine._INCR;
  11670. },
  11671. enumerable: true,
  11672. configurable: true
  11673. });
  11674. Object.defineProperty(Engine, "DECR", {
  11675. /** Passed to stencilOperation to specify that stencil value must be decremented */
  11676. get: function () {
  11677. return Engine._DECR;
  11678. },
  11679. enumerable: true,
  11680. configurable: true
  11681. });
  11682. Object.defineProperty(Engine, "INVERT", {
  11683. /** Passed to stencilOperation to specify that stencil value must be inverted */
  11684. get: function () {
  11685. return Engine._INVERT;
  11686. },
  11687. enumerable: true,
  11688. configurable: true
  11689. });
  11690. Object.defineProperty(Engine, "INCR_WRAP", {
  11691. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  11692. get: function () {
  11693. return Engine._INCR_WRAP;
  11694. },
  11695. enumerable: true,
  11696. configurable: true
  11697. });
  11698. Object.defineProperty(Engine, "DECR_WRAP", {
  11699. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  11700. get: function () {
  11701. return Engine._DECR_WRAP;
  11702. },
  11703. enumerable: true,
  11704. configurable: true
  11705. });
  11706. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  11707. // Alpha
  11708. /** Defines that alpha blending is disabled */
  11709. get: function () {
  11710. return Engine._ALPHA_DISABLE;
  11711. },
  11712. enumerable: true,
  11713. configurable: true
  11714. });
  11715. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  11716. /** Defines that alpha blending to SRC + DEST */
  11717. get: function () {
  11718. return Engine._ALPHA_ONEONE;
  11719. },
  11720. enumerable: true,
  11721. configurable: true
  11722. });
  11723. Object.defineProperty(Engine, "ALPHA_ADD", {
  11724. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  11725. get: function () {
  11726. return Engine._ALPHA_ADD;
  11727. },
  11728. enumerable: true,
  11729. configurable: true
  11730. });
  11731. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  11732. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  11733. get: function () {
  11734. return Engine._ALPHA_COMBINE;
  11735. },
  11736. enumerable: true,
  11737. configurable: true
  11738. });
  11739. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  11740. /** Defines that alpha blending to DEST - SRC * DEST */
  11741. get: function () {
  11742. return Engine._ALPHA_SUBTRACT;
  11743. },
  11744. enumerable: true,
  11745. configurable: true
  11746. });
  11747. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  11748. /** Defines that alpha blending to SRC * DEST */
  11749. get: function () {
  11750. return Engine._ALPHA_MULTIPLY;
  11751. },
  11752. enumerable: true,
  11753. configurable: true
  11754. });
  11755. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  11756. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  11757. get: function () {
  11758. return Engine._ALPHA_MAXIMIZED;
  11759. },
  11760. enumerable: true,
  11761. configurable: true
  11762. });
  11763. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  11764. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  11765. get: function () {
  11766. return Engine._ALPHA_PREMULTIPLIED;
  11767. },
  11768. enumerable: true,
  11769. configurable: true
  11770. });
  11771. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  11772. /**
  11773. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  11774. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  11775. */
  11776. get: function () {
  11777. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11778. },
  11779. enumerable: true,
  11780. configurable: true
  11781. });
  11782. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  11783. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  11784. get: function () {
  11785. return Engine._ALPHA_INTERPOLATE;
  11786. },
  11787. enumerable: true,
  11788. configurable: true
  11789. });
  11790. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  11791. /**
  11792. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  11793. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  11794. */
  11795. get: function () {
  11796. return Engine._ALPHA_SCREENMODE;
  11797. },
  11798. enumerable: true,
  11799. configurable: true
  11800. });
  11801. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  11802. // Delays
  11803. /** Defines that the ressource is not delayed*/
  11804. get: function () {
  11805. return Engine._DELAYLOADSTATE_NONE;
  11806. },
  11807. enumerable: true,
  11808. configurable: true
  11809. });
  11810. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  11811. /** Defines that the ressource was successfully delay loaded */
  11812. get: function () {
  11813. return Engine._DELAYLOADSTATE_LOADED;
  11814. },
  11815. enumerable: true,
  11816. configurable: true
  11817. });
  11818. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  11819. /** Defines that the ressource is currently delay loading */
  11820. get: function () {
  11821. return Engine._DELAYLOADSTATE_LOADING;
  11822. },
  11823. enumerable: true,
  11824. configurable: true
  11825. });
  11826. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  11827. /** Defines that the ressource is delayed and has not started loading */
  11828. get: function () {
  11829. return Engine._DELAYLOADSTATE_NOTLOADED;
  11830. },
  11831. enumerable: true,
  11832. configurable: true
  11833. });
  11834. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  11835. /** ALPHA */
  11836. get: function () {
  11837. return Engine._TEXTUREFORMAT_ALPHA;
  11838. },
  11839. enumerable: true,
  11840. configurable: true
  11841. });
  11842. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  11843. /** LUMINANCE */
  11844. get: function () {
  11845. return Engine._TEXTUREFORMAT_LUMINANCE;
  11846. },
  11847. enumerable: true,
  11848. configurable: true
  11849. });
  11850. Object.defineProperty(Engine, "TEXTUREFORMAT_R32F", {
  11851. /**
  11852. * R32F
  11853. */
  11854. get: function () {
  11855. return Engine._TEXTUREFORMAT_R32F;
  11856. },
  11857. enumerable: true,
  11858. configurable: true
  11859. });
  11860. Object.defineProperty(Engine, "TEXTUREFORMAT_RG32F", {
  11861. /**
  11862. * RG32F
  11863. */
  11864. get: function () {
  11865. return Engine._TEXTUREFORMAT_RG32F;
  11866. },
  11867. enumerable: true,
  11868. configurable: true
  11869. });
  11870. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB32F", {
  11871. /**
  11872. * RGB32F
  11873. */
  11874. get: function () {
  11875. return Engine._TEXTUREFORMAT_RGB32F;
  11876. },
  11877. enumerable: true,
  11878. configurable: true
  11879. });
  11880. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA32F", {
  11881. /**
  11882. * RGBA32F
  11883. */
  11884. get: function () {
  11885. return Engine._TEXTUREFORMAT_RGBA32F;
  11886. },
  11887. enumerable: true,
  11888. configurable: true
  11889. });
  11890. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  11891. /** LUMINANCE_ALPHA */
  11892. get: function () {
  11893. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  11894. },
  11895. enumerable: true,
  11896. configurable: true
  11897. });
  11898. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  11899. /** RGB */
  11900. get: function () {
  11901. return Engine._TEXTUREFORMAT_RGB;
  11902. },
  11903. enumerable: true,
  11904. configurable: true
  11905. });
  11906. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  11907. /** RGBA */
  11908. get: function () {
  11909. return Engine._TEXTUREFORMAT_RGBA;
  11910. },
  11911. enumerable: true,
  11912. configurable: true
  11913. });
  11914. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  11915. /** UNSIGNED_INT */
  11916. get: function () {
  11917. return Engine._TEXTURETYPE_UNSIGNED_INT;
  11918. },
  11919. enumerable: true,
  11920. configurable: true
  11921. });
  11922. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  11923. /** FLOAT */
  11924. get: function () {
  11925. return Engine._TEXTURETYPE_FLOAT;
  11926. },
  11927. enumerable: true,
  11928. configurable: true
  11929. });
  11930. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  11931. /** HALF_FLOAT */
  11932. get: function () {
  11933. return Engine._TEXTURETYPE_HALF_FLOAT;
  11934. },
  11935. enumerable: true,
  11936. configurable: true
  11937. });
  11938. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  11939. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  11940. get: function () {
  11941. return Engine._SCALEMODE_FLOOR;
  11942. },
  11943. enumerable: true,
  11944. configurable: true
  11945. });
  11946. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  11947. /** Defines that texture rescaling will look for the nearest power of 2 size */
  11948. get: function () {
  11949. return Engine._SCALEMODE_NEAREST;
  11950. },
  11951. enumerable: true,
  11952. configurable: true
  11953. });
  11954. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  11955. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  11956. get: function () {
  11957. return Engine._SCALEMODE_CEILING;
  11958. },
  11959. enumerable: true,
  11960. configurable: true
  11961. });
  11962. Object.defineProperty(Engine, "Version", {
  11963. /**
  11964. * Returns the current version of the framework
  11965. */
  11966. get: function () {
  11967. return "3.2.0-rc.4";
  11968. },
  11969. enumerable: true,
  11970. configurable: true
  11971. });
  11972. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  11973. /**
  11974. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  11975. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  11976. */
  11977. get: function () {
  11978. return this._vrExclusivePointerMode;
  11979. },
  11980. enumerable: true,
  11981. configurable: true
  11982. });
  11983. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  11984. /**
  11985. * Gets a boolean indicating that the engine supports uniform buffers
  11986. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  11987. */
  11988. get: function () {
  11989. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  11990. },
  11991. enumerable: true,
  11992. configurable: true
  11993. });
  11994. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  11995. /**
  11996. * Gets a boolean indicating that only power of 2 textures are supported
  11997. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  11998. */
  11999. get: function () {
  12000. return this._webGLVersion < 2 || this.forcePOTTextures;
  12001. },
  12002. enumerable: true,
  12003. configurable: true
  12004. });
  12005. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  12006. /**
  12007. * Gets the performance monitor attached to this engine
  12008. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  12009. */
  12010. get: function () {
  12011. return this._performanceMonitor;
  12012. },
  12013. enumerable: true,
  12014. configurable: true
  12015. });
  12016. Object.defineProperty(Engine.prototype, "texturesSupported", {
  12017. /**
  12018. * Gets the list of texture formats supported
  12019. */
  12020. get: function () {
  12021. return this._texturesSupported;
  12022. },
  12023. enumerable: true,
  12024. configurable: true
  12025. });
  12026. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  12027. /**
  12028. * Gets the list of texture formats in use
  12029. */
  12030. get: function () {
  12031. return this._textureFormatInUse;
  12032. },
  12033. enumerable: true,
  12034. configurable: true
  12035. });
  12036. Object.defineProperty(Engine.prototype, "currentViewport", {
  12037. /**
  12038. * Gets the current viewport
  12039. */
  12040. get: function () {
  12041. return this._cachedViewport;
  12042. },
  12043. enumerable: true,
  12044. configurable: true
  12045. });
  12046. Object.defineProperty(Engine.prototype, "emptyTexture", {
  12047. /**
  12048. * Gets the default empty texture
  12049. */
  12050. get: function () {
  12051. if (!this._emptyTexture) {
  12052. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12053. }
  12054. return this._emptyTexture;
  12055. },
  12056. enumerable: true,
  12057. configurable: true
  12058. });
  12059. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  12060. /**
  12061. * Gets the default empty 3D texture
  12062. */
  12063. get: function () {
  12064. if (!this._emptyTexture3D) {
  12065. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12066. }
  12067. return this._emptyTexture3D;
  12068. },
  12069. enumerable: true,
  12070. configurable: true
  12071. });
  12072. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  12073. /**
  12074. * Gets the default empty cube texture
  12075. */
  12076. get: function () {
  12077. if (!this._emptyCubeTexture) {
  12078. var faceData = new Uint8Array(4);
  12079. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  12080. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12081. }
  12082. return this._emptyCubeTexture;
  12083. },
  12084. enumerable: true,
  12085. configurable: true
  12086. });
  12087. Engine.prototype._rebuildInternalTextures = function () {
  12088. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  12089. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  12090. var internalTexture = currentState_1[_i];
  12091. internalTexture._rebuild();
  12092. }
  12093. };
  12094. Engine.prototype._rebuildEffects = function () {
  12095. for (var key in this._compiledEffects) {
  12096. var effect = this._compiledEffects[key];
  12097. effect._prepareEffect();
  12098. }
  12099. BABYLON.Effect.ResetCache();
  12100. };
  12101. Engine.prototype._rebuildBuffers = function () {
  12102. // Index / Vertex
  12103. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  12104. var scene = _a[_i];
  12105. scene.resetCachedMaterial();
  12106. scene._rebuildGeometries();
  12107. scene._rebuildTextures();
  12108. }
  12109. // Uniforms
  12110. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  12111. var uniformBuffer = _c[_b];
  12112. uniformBuffer._rebuild();
  12113. }
  12114. };
  12115. Engine.prototype._initGLContext = function () {
  12116. // Caps
  12117. this._caps = new EngineCapabilities();
  12118. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  12119. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12120. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  12121. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  12122. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  12123. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  12124. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  12125. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12126. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12127. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12128. // Infos
  12129. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12130. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12131. if (rendererInfo != null) {
  12132. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12133. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12134. }
  12135. if (!this._glVendor) {
  12136. this._glVendor = "Unknown vendor";
  12137. }
  12138. if (!this._glRenderer) {
  12139. this._glRenderer = "Unknown renderer";
  12140. }
  12141. // Constants
  12142. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12143. if (this._gl.RGBA16F !== 0x881A) {
  12144. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12145. }
  12146. if (this._gl.RGBA32F !== 0x8814) {
  12147. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12148. }
  12149. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12150. this._gl.DEPTH24_STENCIL8 = 35056;
  12151. }
  12152. // Extensions
  12153. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12154. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12155. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12156. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12157. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12158. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12159. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12160. 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');
  12161. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12162. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12163. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12164. this._caps.highPrecisionShaderSupported = true;
  12165. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12166. if (this._caps.timerQuery) {
  12167. if (this._webGLVersion === 1) {
  12168. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12169. }
  12170. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12171. }
  12172. // Checks if some of the format renders first to allow the use of webgl inspector.
  12173. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12174. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12175. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12176. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12177. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12178. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12179. if (this._webGLVersion > 1) {
  12180. this._gl.HALF_FLOAT_OES = 0x140B;
  12181. }
  12182. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12183. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12184. // Draw buffers
  12185. if (this._webGLVersion > 1) {
  12186. this._caps.drawBuffersExtension = true;
  12187. }
  12188. else {
  12189. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12190. if (drawBuffersExtension !== null) {
  12191. this._caps.drawBuffersExtension = true;
  12192. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12193. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12194. for (var i = 0; i < 16; i++) {
  12195. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12196. }
  12197. }
  12198. else {
  12199. this._caps.drawBuffersExtension = false;
  12200. }
  12201. }
  12202. // Depth Texture
  12203. if (this._webGLVersion > 1) {
  12204. this._caps.depthTextureExtension = true;
  12205. }
  12206. else {
  12207. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12208. if (depthTextureExtension != null) {
  12209. this._caps.depthTextureExtension = true;
  12210. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12211. }
  12212. }
  12213. // Vertex array object
  12214. if (this._webGLVersion > 1) {
  12215. this._caps.vertexArrayObject = true;
  12216. }
  12217. else {
  12218. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12219. if (vertexArrayObjectExtension != null) {
  12220. this._caps.vertexArrayObject = true;
  12221. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12222. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12223. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12224. }
  12225. else {
  12226. this._caps.vertexArrayObject = false;
  12227. }
  12228. }
  12229. // Instances count
  12230. if (this._webGLVersion > 1) {
  12231. this._caps.instancedArrays = true;
  12232. }
  12233. else {
  12234. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12235. if (instanceExtension != null) {
  12236. this._caps.instancedArrays = true;
  12237. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12238. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12239. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12240. }
  12241. else {
  12242. this._caps.instancedArrays = false;
  12243. }
  12244. }
  12245. // Intelligently add supported compressed formats in order to check for.
  12246. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12247. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12248. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12249. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12250. if (this._caps.astc)
  12251. this.texturesSupported.push('-astc.ktx');
  12252. if (this._caps.s3tc)
  12253. this.texturesSupported.push('-dxt.ktx');
  12254. if (this._caps.pvrtc)
  12255. this.texturesSupported.push('-pvrtc.ktx');
  12256. if (this._caps.etc2)
  12257. this.texturesSupported.push('-etc2.ktx');
  12258. if (this._caps.etc1)
  12259. this.texturesSupported.push('-etc1.ktx');
  12260. if (this._gl.getShaderPrecisionFormat) {
  12261. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12262. if (highp) {
  12263. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12264. }
  12265. }
  12266. // Depth buffer
  12267. this.setDepthBuffer(true);
  12268. this.setDepthFunctionToLessOrEqual();
  12269. this.setDepthWrite(true);
  12270. // Texture maps
  12271. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12272. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12273. this._nextFreeTextureSlots.push(slot);
  12274. }
  12275. };
  12276. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12277. /**
  12278. * Gets version of the current webGL context
  12279. */
  12280. get: function () {
  12281. return this._webGLVersion;
  12282. },
  12283. enumerable: true,
  12284. configurable: true
  12285. });
  12286. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12287. /**
  12288. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12289. */
  12290. get: function () {
  12291. return this._isStencilEnable;
  12292. },
  12293. enumerable: true,
  12294. configurable: true
  12295. });
  12296. Engine.prototype._prepareWorkingCanvas = function () {
  12297. if (this._workingCanvas) {
  12298. return;
  12299. }
  12300. this._workingCanvas = document.createElement("canvas");
  12301. var context = this._workingCanvas.getContext("2d");
  12302. if (context) {
  12303. this._workingContext = context;
  12304. }
  12305. };
  12306. /**
  12307. * Reset the texture cache to empty state
  12308. */
  12309. Engine.prototype.resetTextureCache = function () {
  12310. for (var key in this._boundTexturesCache) {
  12311. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12312. continue;
  12313. }
  12314. var boundTexture = this._boundTexturesCache[key];
  12315. if (boundTexture) {
  12316. this._removeDesignatedSlot(boundTexture);
  12317. }
  12318. this._boundTexturesCache[key] = null;
  12319. }
  12320. if (!this.disableTextureBindingOptimization) {
  12321. this._nextFreeTextureSlots = [];
  12322. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12323. this._nextFreeTextureSlots.push(slot);
  12324. }
  12325. }
  12326. this._currentTextureChannel = -1;
  12327. };
  12328. /**
  12329. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12330. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12331. * @returns true if engine is in deterministic lock step mode
  12332. */
  12333. Engine.prototype.isDeterministicLockStep = function () {
  12334. return this._deterministicLockstep;
  12335. };
  12336. /**
  12337. * Gets the max steps when engine is running in deterministic lock step
  12338. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12339. * @returns the max steps
  12340. */
  12341. Engine.prototype.getLockstepMaxSteps = function () {
  12342. return this._lockstepMaxSteps;
  12343. };
  12344. /**
  12345. * Gets an object containing information about the current webGL context
  12346. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12347. */
  12348. Engine.prototype.getGlInfo = function () {
  12349. return {
  12350. vendor: this._glVendor,
  12351. renderer: this._glRenderer,
  12352. version: this._glVersion
  12353. };
  12354. };
  12355. /**
  12356. * Gets current aspect ratio
  12357. * @param camera defines the camera to use to get the aspect ratio
  12358. * @param useScreen defines if screen size must be used (or the current render target if any)
  12359. * @returns a number defining the aspect ratio
  12360. */
  12361. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12362. if (useScreen === void 0) { useScreen = false; }
  12363. var viewport = camera.viewport;
  12364. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12365. };
  12366. /**
  12367. * Gets the current render width
  12368. * @param useScreen defines if screen size must be used (or the current render target if any)
  12369. * @returns a number defining the current render width
  12370. */
  12371. Engine.prototype.getRenderWidth = function (useScreen) {
  12372. if (useScreen === void 0) { useScreen = false; }
  12373. if (!useScreen && this._currentRenderTarget) {
  12374. return this._currentRenderTarget.width;
  12375. }
  12376. return this._gl.drawingBufferWidth;
  12377. };
  12378. /**
  12379. * Gets the current render height
  12380. * @param useScreen defines if screen size must be used (or the current render target if any)
  12381. * @returns a number defining the current render height
  12382. */
  12383. Engine.prototype.getRenderHeight = function (useScreen) {
  12384. if (useScreen === void 0) { useScreen = false; }
  12385. if (!useScreen && this._currentRenderTarget) {
  12386. return this._currentRenderTarget.height;
  12387. }
  12388. return this._gl.drawingBufferHeight;
  12389. };
  12390. /**
  12391. * Gets the HTML canvas attached with the current webGL context
  12392. * @returns a HTML canvas
  12393. */
  12394. Engine.prototype.getRenderingCanvas = function () {
  12395. return this._renderingCanvas;
  12396. };
  12397. /**
  12398. * Gets the client rect of the HTML canvas attached with the current webGL context
  12399. * @returns a client rectanglee
  12400. */
  12401. Engine.prototype.getRenderingCanvasClientRect = function () {
  12402. if (!this._renderingCanvas) {
  12403. return null;
  12404. }
  12405. return this._renderingCanvas.getBoundingClientRect();
  12406. };
  12407. /**
  12408. * Defines the hardware scaling level.
  12409. * By default the hardware scaling level is computed from the window device ratio.
  12410. * 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.
  12411. * @param level defines the level to use
  12412. */
  12413. Engine.prototype.setHardwareScalingLevel = function (level) {
  12414. this._hardwareScalingLevel = level;
  12415. this.resize();
  12416. };
  12417. /**
  12418. * Gets the current hardware scaling level.
  12419. * By default the hardware scaling level is computed from the window device ratio.
  12420. * 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.
  12421. * @returns a number indicating the current hardware scaling level
  12422. */
  12423. Engine.prototype.getHardwareScalingLevel = function () {
  12424. return this._hardwareScalingLevel;
  12425. };
  12426. /**
  12427. * Gets the list of loaded textures
  12428. * @returns an array containing all loaded textures
  12429. */
  12430. Engine.prototype.getLoadedTexturesCache = function () {
  12431. return this._internalTexturesCache;
  12432. };
  12433. /**
  12434. * Gets the object containing all engine capabilities
  12435. * @returns the EngineCapabilities object
  12436. */
  12437. Engine.prototype.getCaps = function () {
  12438. return this._caps;
  12439. };
  12440. Object.defineProperty(Engine.prototype, "drawCalls", {
  12441. /** @hidden */
  12442. get: function () {
  12443. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12444. return 0;
  12445. },
  12446. enumerable: true,
  12447. configurable: true
  12448. });
  12449. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12450. /** @hidden */
  12451. get: function () {
  12452. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12453. return null;
  12454. },
  12455. enumerable: true,
  12456. configurable: true
  12457. });
  12458. /**
  12459. * Gets the current depth function
  12460. * @returns a number defining the depth function
  12461. */
  12462. Engine.prototype.getDepthFunction = function () {
  12463. return this._depthCullingState.depthFunc;
  12464. };
  12465. /**
  12466. * Sets the current depth function
  12467. * @param depthFunc defines the function to use
  12468. */
  12469. Engine.prototype.setDepthFunction = function (depthFunc) {
  12470. this._depthCullingState.depthFunc = depthFunc;
  12471. };
  12472. /**
  12473. * Sets the current depth function to GREATER
  12474. */
  12475. Engine.prototype.setDepthFunctionToGreater = function () {
  12476. this._depthCullingState.depthFunc = this._gl.GREATER;
  12477. };
  12478. /**
  12479. * Sets the current depth function to GEQUAL
  12480. */
  12481. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12482. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12483. };
  12484. /**
  12485. * Sets the current depth function to LESS
  12486. */
  12487. Engine.prototype.setDepthFunctionToLess = function () {
  12488. this._depthCullingState.depthFunc = this._gl.LESS;
  12489. };
  12490. /**
  12491. * Sets the current depth function to LEQUAL
  12492. */
  12493. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12494. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12495. };
  12496. /**
  12497. * Gets a boolean indicating if stencil buffer is enabled
  12498. * @returns the current stencil buffer state
  12499. */
  12500. Engine.prototype.getStencilBuffer = function () {
  12501. return this._stencilState.stencilTest;
  12502. };
  12503. /**
  12504. * Enable or disable the stencil buffer
  12505. * @param enable defines if the stencil buffer must be enabled or disabled
  12506. */
  12507. Engine.prototype.setStencilBuffer = function (enable) {
  12508. this._stencilState.stencilTest = enable;
  12509. };
  12510. /**
  12511. * Gets the current stencil mask
  12512. * @returns a number defining the new stencil mask to use
  12513. */
  12514. Engine.prototype.getStencilMask = function () {
  12515. return this._stencilState.stencilMask;
  12516. };
  12517. /**
  12518. * Sets the current stencil mask
  12519. * @param mask defines the new stencil mask to use
  12520. */
  12521. Engine.prototype.setStencilMask = function (mask) {
  12522. this._stencilState.stencilMask = mask;
  12523. };
  12524. /**
  12525. * Gets the current stencil function
  12526. * @returns a number defining the stencil function to use
  12527. */
  12528. Engine.prototype.getStencilFunction = function () {
  12529. return this._stencilState.stencilFunc;
  12530. };
  12531. /**
  12532. * Gets the current stencil reference value
  12533. * @returns a number defining the stencil reference value to use
  12534. */
  12535. Engine.prototype.getStencilFunctionReference = function () {
  12536. return this._stencilState.stencilFuncRef;
  12537. };
  12538. /**
  12539. * Gets the current stencil mask
  12540. * @returns a number defining the stencil mask to use
  12541. */
  12542. Engine.prototype.getStencilFunctionMask = function () {
  12543. return this._stencilState.stencilFuncMask;
  12544. };
  12545. /**
  12546. * Sets the current stencil function
  12547. * @param stencilFunc defines the new stencil function to use
  12548. */
  12549. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12550. this._stencilState.stencilFunc = stencilFunc;
  12551. };
  12552. /**
  12553. * Sets the current stencil reference
  12554. * @param reference defines the new stencil reference to use
  12555. */
  12556. Engine.prototype.setStencilFunctionReference = function (reference) {
  12557. this._stencilState.stencilFuncRef = reference;
  12558. };
  12559. /**
  12560. * Sets the current stencil mask
  12561. * @param mask defines the new stencil mask to use
  12562. */
  12563. Engine.prototype.setStencilFunctionMask = function (mask) {
  12564. this._stencilState.stencilFuncMask = mask;
  12565. };
  12566. /**
  12567. * Gets the current stencil operation when stencil fails
  12568. * @returns a number defining stencil operation to use when stencil fails
  12569. */
  12570. Engine.prototype.getStencilOperationFail = function () {
  12571. return this._stencilState.stencilOpStencilFail;
  12572. };
  12573. /**
  12574. * Gets the current stencil operation when depth fails
  12575. * @returns a number defining stencil operation to use when depth fails
  12576. */
  12577. Engine.prototype.getStencilOperationDepthFail = function () {
  12578. return this._stencilState.stencilOpDepthFail;
  12579. };
  12580. /**
  12581. * Gets the current stencil operation when stencil passes
  12582. * @returns a number defining stencil operation to use when stencil passes
  12583. */
  12584. Engine.prototype.getStencilOperationPass = function () {
  12585. return this._stencilState.stencilOpStencilDepthPass;
  12586. };
  12587. /**
  12588. * Sets the stencil operation to use when stencil fails
  12589. * @param operation defines the stencil operation to use when stencil fails
  12590. */
  12591. Engine.prototype.setStencilOperationFail = function (operation) {
  12592. this._stencilState.stencilOpStencilFail = operation;
  12593. };
  12594. /**
  12595. * Sets the stencil operation to use when depth fails
  12596. * @param operation defines the stencil operation to use when depth fails
  12597. */
  12598. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12599. this._stencilState.stencilOpDepthFail = operation;
  12600. };
  12601. /**
  12602. * Sets the stencil operation to use when stencil passes
  12603. * @param operation defines the stencil operation to use when stencil passes
  12604. */
  12605. Engine.prototype.setStencilOperationPass = function (operation) {
  12606. this._stencilState.stencilOpStencilDepthPass = operation;
  12607. };
  12608. /**
  12609. * Sets a boolean indicating if the dithering state is enabled or disabled
  12610. * @param value defines the dithering state
  12611. */
  12612. Engine.prototype.setDitheringState = function (value) {
  12613. if (value) {
  12614. this._gl.enable(this._gl.DITHER);
  12615. }
  12616. else {
  12617. this._gl.disable(this._gl.DITHER);
  12618. }
  12619. };
  12620. /**
  12621. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12622. * @param value defines the rasterizer state
  12623. */
  12624. Engine.prototype.setRasterizerState = function (value) {
  12625. if (value) {
  12626. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12627. }
  12628. else {
  12629. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12630. }
  12631. };
  12632. /**
  12633. * stop executing a render loop function and remove it from the execution array
  12634. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12635. */
  12636. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12637. if (!renderFunction) {
  12638. this._activeRenderLoops = [];
  12639. return;
  12640. }
  12641. var index = this._activeRenderLoops.indexOf(renderFunction);
  12642. if (index >= 0) {
  12643. this._activeRenderLoops.splice(index, 1);
  12644. }
  12645. };
  12646. /** @hidden */
  12647. Engine.prototype._renderLoop = function () {
  12648. if (!this._contextWasLost) {
  12649. var shouldRender = true;
  12650. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12651. shouldRender = false;
  12652. }
  12653. if (shouldRender) {
  12654. // Start new frame
  12655. this.beginFrame();
  12656. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12657. var renderFunction = this._activeRenderLoops[index];
  12658. renderFunction();
  12659. }
  12660. // Present
  12661. this.endFrame();
  12662. }
  12663. }
  12664. if (this._activeRenderLoops.length > 0) {
  12665. // Register new frame
  12666. var requester = null;
  12667. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12668. requester = this._vrDisplay;
  12669. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12670. }
  12671. else {
  12672. this._renderingQueueLaunched = false;
  12673. }
  12674. };
  12675. /**
  12676. * Register and execute a render loop. The engine can have more than one render function
  12677. * @param renderFunction defines the function to continuously execute
  12678. */
  12679. Engine.prototype.runRenderLoop = function (renderFunction) {
  12680. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12681. return;
  12682. }
  12683. this._activeRenderLoops.push(renderFunction);
  12684. if (!this._renderingQueueLaunched) {
  12685. this._renderingQueueLaunched = true;
  12686. this._bindedRenderFunction = this._renderLoop.bind(this);
  12687. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12688. }
  12689. };
  12690. /**
  12691. * Toggle full screen mode
  12692. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12693. * @param options defines an option object to be sent to the requestFullscreen function
  12694. */
  12695. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12696. if (this.isFullscreen) {
  12697. BABYLON.Tools.ExitFullscreen();
  12698. }
  12699. else {
  12700. this._pointerLockRequested = requestPointerLock;
  12701. if (this._renderingCanvas) {
  12702. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12703. }
  12704. }
  12705. };
  12706. /**
  12707. * Clear the current render buffer or the current render target (if any is set up)
  12708. * @param color defines the color to use
  12709. * @param backBuffer defines if the back buffer must be cleared
  12710. * @param depth defines if the depth buffer must be cleared
  12711. * @param stencil defines if the stencil buffer must be cleared
  12712. */
  12713. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12714. if (stencil === void 0) { stencil = false; }
  12715. this.applyStates();
  12716. var mode = 0;
  12717. if (backBuffer && color) {
  12718. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12719. mode |= this._gl.COLOR_BUFFER_BIT;
  12720. }
  12721. if (depth) {
  12722. this._gl.clearDepth(1.0);
  12723. mode |= this._gl.DEPTH_BUFFER_BIT;
  12724. }
  12725. if (stencil) {
  12726. this._gl.clearStencil(0);
  12727. mode |= this._gl.STENCIL_BUFFER_BIT;
  12728. }
  12729. this._gl.clear(mode);
  12730. };
  12731. /**
  12732. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12733. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12734. * @param y defines the y-coordinate of the corner of the clear rectangle
  12735. * @param width defines the width of the clear rectangle
  12736. * @param height defines the height of the clear rectangle
  12737. * @param clearColor defines the clear color
  12738. */
  12739. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12740. var gl = this._gl;
  12741. // Save state
  12742. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12743. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12744. // Change state
  12745. gl.enable(gl.SCISSOR_TEST);
  12746. gl.scissor(x, y, width, height);
  12747. // Clear
  12748. this.clear(clearColor, true, true, true);
  12749. // Restore state
  12750. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12751. if (curScissor === true) {
  12752. gl.enable(gl.SCISSOR_TEST);
  12753. }
  12754. else {
  12755. gl.disable(gl.SCISSOR_TEST);
  12756. }
  12757. };
  12758. /**
  12759. * Set the WebGL's viewport
  12760. * @param viewport defines the viewport element to be used
  12761. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12762. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12763. */
  12764. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12765. var width = requiredWidth || this.getRenderWidth();
  12766. var height = requiredHeight || this.getRenderHeight();
  12767. var x = viewport.x || 0;
  12768. var y = viewport.y || 0;
  12769. this._cachedViewport = viewport;
  12770. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12771. };
  12772. /**
  12773. * Directly set the WebGL Viewport
  12774. * @param x defines the x coordinate of the viewport (in screen space)
  12775. * @param y defines the y coordinate of the viewport (in screen space)
  12776. * @param width defines the width of the viewport (in screen space)
  12777. * @param height defines the height of the viewport (in screen space)
  12778. * @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
  12779. */
  12780. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12781. var currentViewport = this._cachedViewport;
  12782. this._cachedViewport = null;
  12783. this._gl.viewport(x, y, width, height);
  12784. return currentViewport;
  12785. };
  12786. /**
  12787. * Begin a new frame
  12788. */
  12789. Engine.prototype.beginFrame = function () {
  12790. this.onBeginFrameObservable.notifyObservers(this);
  12791. this._measureFps();
  12792. };
  12793. /**
  12794. * Enf the current frame
  12795. */
  12796. Engine.prototype.endFrame = function () {
  12797. // Force a flush in case we are using a bad OS.
  12798. if (this._badOS) {
  12799. this.flushFramebuffer();
  12800. }
  12801. // Submit frame to the vr device, if enabled
  12802. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12803. // TODO: We should only submit the frame if we read frameData successfully.
  12804. this._vrDisplay.submitFrame();
  12805. }
  12806. this.onEndFrameObservable.notifyObservers(this);
  12807. };
  12808. /**
  12809. * Resize the view according to the canvas' size
  12810. */
  12811. Engine.prototype.resize = function () {
  12812. // We're not resizing the size of the canvas while in VR mode & presenting
  12813. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12814. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12815. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12816. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12817. }
  12818. };
  12819. /**
  12820. * Force a specific size of the canvas
  12821. * @param width defines the new canvas' width
  12822. * @param height defines the new canvas' height
  12823. */
  12824. Engine.prototype.setSize = function (width, height) {
  12825. if (!this._renderingCanvas) {
  12826. return;
  12827. }
  12828. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12829. return;
  12830. }
  12831. this._renderingCanvas.width = width;
  12832. this._renderingCanvas.height = height;
  12833. for (var index = 0; index < this.scenes.length; index++) {
  12834. var scene = this.scenes[index];
  12835. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12836. var cam = scene.cameras[camIndex];
  12837. cam._currentRenderId = 0;
  12838. }
  12839. }
  12840. if (this.onResizeObservable.hasObservers) {
  12841. this.onResizeObservable.notifyObservers(this);
  12842. }
  12843. };
  12844. // WebVR functions
  12845. /**
  12846. * Gets a boolean indicating if a webVR device was detected
  12847. * @returns true if a webVR device was detected
  12848. */
  12849. Engine.prototype.isVRDevicePresent = function () {
  12850. return !!this._vrDisplay;
  12851. };
  12852. /**
  12853. * Gets the current webVR device
  12854. * @returns the current webVR device (or null)
  12855. */
  12856. Engine.prototype.getVRDevice = function () {
  12857. return this._vrDisplay;
  12858. };
  12859. /**
  12860. * Initializes a webVR display and starts listening to display change events
  12861. * The onVRDisplayChangedObservable will be notified upon these changes
  12862. * @returns The onVRDisplayChangedObservable
  12863. */
  12864. Engine.prototype.initWebVR = function () {
  12865. this.initWebVRAsync();
  12866. return this.onVRDisplayChangedObservable;
  12867. };
  12868. /**
  12869. * Initializes a webVR display and starts listening to display change events
  12870. * The onVRDisplayChangedObservable will be notified upon these changes
  12871. * @returns A promise containing a VRDisplay and if vr is supported
  12872. */
  12873. Engine.prototype.initWebVRAsync = function () {
  12874. var _this = this;
  12875. var notifyObservers = function () {
  12876. var eventArgs = {
  12877. vrDisplay: _this._vrDisplay,
  12878. vrSupported: _this._vrSupported
  12879. };
  12880. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12881. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12882. };
  12883. if (!this._onVrDisplayConnect) {
  12884. this._onVrDisplayConnect = function (event) {
  12885. _this._vrDisplay = event.display;
  12886. notifyObservers();
  12887. };
  12888. this._onVrDisplayDisconnect = function () {
  12889. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12890. _this._vrDisplay = undefined;
  12891. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  12892. notifyObservers();
  12893. };
  12894. this._onVrDisplayPresentChange = function () {
  12895. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  12896. };
  12897. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  12898. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  12899. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  12900. }
  12901. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  12902. this._webVRInitPromise.then(notifyObservers);
  12903. return this._webVRInitPromise;
  12904. };
  12905. /**
  12906. * Call this function to switch to webVR mode
  12907. * Will do nothing if webVR is not supported or if there is no webVR device
  12908. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12909. */
  12910. Engine.prototype.enableVR = function () {
  12911. var _this = this;
  12912. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  12913. var onResolved = function () {
  12914. _this.onVRRequestPresentComplete.notifyObservers(true);
  12915. _this._onVRFullScreenTriggered();
  12916. };
  12917. var onRejected = function () {
  12918. _this.onVRRequestPresentComplete.notifyObservers(false);
  12919. };
  12920. this.onVRRequestPresentStart.notifyObservers(this);
  12921. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  12922. }
  12923. };
  12924. /**
  12925. * Call this function to leave webVR mode
  12926. * Will do nothing if webVR is not supported or if there is no webVR device
  12927. * @see http://doc.babylonjs.com/how_to/webvr_camera
  12928. */
  12929. Engine.prototype.disableVR = function () {
  12930. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12931. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  12932. }
  12933. };
  12934. Engine.prototype._getVRDisplaysAsync = function () {
  12935. var _this = this;
  12936. return new Promise(function (res, rej) {
  12937. if (navigator.getVRDisplays) {
  12938. navigator.getVRDisplays().then(function (devices) {
  12939. _this._vrSupported = true;
  12940. // note that devices may actually be an empty array. This is fine;
  12941. // we expect this._vrDisplay to be undefined in this case.
  12942. _this._vrDisplay = devices[0];
  12943. res({
  12944. vrDisplay: _this._vrDisplay,
  12945. vrSupported: _this._vrSupported
  12946. });
  12947. });
  12948. }
  12949. else {
  12950. _this._vrDisplay = undefined;
  12951. _this._vrSupported = false;
  12952. res({
  12953. vrDisplay: _this._vrDisplay,
  12954. vrSupported: _this._vrSupported
  12955. });
  12956. }
  12957. });
  12958. };
  12959. /**
  12960. * Binds the frame buffer to the specified texture.
  12961. * @param texture The texture to render to or null for the default canvas
  12962. * @param faceIndex The face of the texture to render to in case of cube texture
  12963. * @param requiredWidth The width of the target to render to
  12964. * @param requiredHeight The height of the target to render to
  12965. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  12966. * @param depthStencilTexture The depth stencil texture to use to render
  12967. */
  12968. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture) {
  12969. if (this._currentRenderTarget) {
  12970. this.unBindFramebuffer(this._currentRenderTarget);
  12971. }
  12972. this._currentRenderTarget = texture;
  12973. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  12974. var gl = this._gl;
  12975. if (texture.isCube) {
  12976. if (faceIndex === undefined) {
  12977. faceIndex = 0;
  12978. }
  12979. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  12980. if (depthStencilTexture) {
  12981. if (depthStencilTexture._generateStencilBuffer) {
  12982. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  12983. }
  12984. else {
  12985. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  12986. }
  12987. }
  12988. }
  12989. if (this._cachedViewport && !forceFullscreenViewport) {
  12990. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  12991. }
  12992. else {
  12993. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  12994. }
  12995. this.wipeCaches();
  12996. };
  12997. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  12998. if (this._currentFramebuffer !== framebuffer) {
  12999. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  13000. this._currentFramebuffer = framebuffer;
  13001. }
  13002. };
  13003. /**
  13004. * Unbind the current render target texture from the webGL context
  13005. * @param texture defines the render target texture to unbind
  13006. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13007. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13008. */
  13009. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  13010. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13011. this._currentRenderTarget = null;
  13012. // If MSAA, we need to bitblt back to main texture
  13013. var gl = this._gl;
  13014. if (texture._MSAAFramebuffer) {
  13015. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  13016. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  13017. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13018. }
  13019. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13020. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13021. gl.generateMipmap(gl.TEXTURE_2D);
  13022. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13023. }
  13024. if (onBeforeUnbind) {
  13025. if (texture._MSAAFramebuffer) {
  13026. // Bind the correct framebuffer
  13027. this.bindUnboundFramebuffer(texture._framebuffer);
  13028. }
  13029. onBeforeUnbind();
  13030. }
  13031. this.bindUnboundFramebuffer(null);
  13032. };
  13033. /**
  13034. * Unbind a list of render target textures from the webGL context
  13035. * This is used only when drawBuffer extension or webGL2 are active
  13036. * @param textures defines the render target textures to unbind
  13037. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13038. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13039. */
  13040. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  13041. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13042. this._currentRenderTarget = null;
  13043. // If MSAA, we need to bitblt back to main texture
  13044. var gl = this._gl;
  13045. if (textures[0]._MSAAFramebuffer) {
  13046. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  13047. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  13048. var attachments = textures[0]._attachments;
  13049. if (!attachments) {
  13050. attachments = new Array(textures.length);
  13051. textures[0]._attachments = attachments;
  13052. }
  13053. for (var i = 0; i < textures.length; i++) {
  13054. var texture = textures[i];
  13055. for (var j = 0; j < attachments.length; j++) {
  13056. attachments[j] = gl.NONE;
  13057. }
  13058. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13059. gl.readBuffer(attachments[i]);
  13060. gl.drawBuffers(attachments);
  13061. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13062. }
  13063. for (var i = 0; i < attachments.length; i++) {
  13064. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13065. }
  13066. gl.drawBuffers(attachments);
  13067. }
  13068. for (var i = 0; i < textures.length; i++) {
  13069. var texture = textures[i];
  13070. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13071. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  13072. gl.generateMipmap(gl.TEXTURE_2D);
  13073. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13074. }
  13075. }
  13076. if (onBeforeUnbind) {
  13077. if (textures[0]._MSAAFramebuffer) {
  13078. // Bind the correct framebuffer
  13079. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13080. }
  13081. onBeforeUnbind();
  13082. }
  13083. this.bindUnboundFramebuffer(null);
  13084. };
  13085. /**
  13086. * Force the mipmap generation for the given render target texture
  13087. * @param texture defines the render target texture to use
  13088. */
  13089. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  13090. if (texture.generateMipMaps) {
  13091. var gl = this._gl;
  13092. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13093. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13094. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13095. }
  13096. };
  13097. /**
  13098. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13099. */
  13100. Engine.prototype.flushFramebuffer = function () {
  13101. this._gl.flush();
  13102. };
  13103. /**
  13104. * Unbind the current render target and bind the default framebuffer
  13105. */
  13106. Engine.prototype.restoreDefaultFramebuffer = function () {
  13107. if (this._currentRenderTarget) {
  13108. this.unBindFramebuffer(this._currentRenderTarget);
  13109. }
  13110. else {
  13111. this.bindUnboundFramebuffer(null);
  13112. }
  13113. if (this._cachedViewport) {
  13114. this.setViewport(this._cachedViewport);
  13115. }
  13116. this.wipeCaches();
  13117. };
  13118. // UBOs
  13119. /**
  13120. * Create an uniform buffer
  13121. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13122. * @param elements defines the content of the uniform buffer
  13123. * @returns the webGL uniform buffer
  13124. */
  13125. Engine.prototype.createUniformBuffer = function (elements) {
  13126. var ubo = this._gl.createBuffer();
  13127. if (!ubo) {
  13128. throw new Error("Unable to create uniform buffer");
  13129. }
  13130. this.bindUniformBuffer(ubo);
  13131. if (elements instanceof Float32Array) {
  13132. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13133. }
  13134. else {
  13135. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13136. }
  13137. this.bindUniformBuffer(null);
  13138. ubo.references = 1;
  13139. return ubo;
  13140. };
  13141. /**
  13142. * Create a dynamic uniform buffer
  13143. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13144. * @param elements defines the content of the uniform buffer
  13145. * @returns the webGL uniform buffer
  13146. */
  13147. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13148. var ubo = this._gl.createBuffer();
  13149. if (!ubo) {
  13150. throw new Error("Unable to create dynamic uniform buffer");
  13151. }
  13152. this.bindUniformBuffer(ubo);
  13153. if (elements instanceof Float32Array) {
  13154. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13155. }
  13156. else {
  13157. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13158. }
  13159. this.bindUniformBuffer(null);
  13160. ubo.references = 1;
  13161. return ubo;
  13162. };
  13163. /**
  13164. * Update an existing uniform buffer
  13165. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13166. * @param uniformBuffer defines the target uniform buffer
  13167. * @param elements defines the content to update
  13168. * @param offset defines the offset in the uniform buffer where update should start
  13169. * @param count defines the size of the data to update
  13170. */
  13171. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13172. this.bindUniformBuffer(uniformBuffer);
  13173. if (offset === undefined) {
  13174. offset = 0;
  13175. }
  13176. if (count === undefined) {
  13177. if (elements instanceof Float32Array) {
  13178. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13179. }
  13180. else {
  13181. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13182. }
  13183. }
  13184. else {
  13185. if (elements instanceof Float32Array) {
  13186. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13187. }
  13188. else {
  13189. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13190. }
  13191. }
  13192. this.bindUniformBuffer(null);
  13193. };
  13194. // VBOs
  13195. Engine.prototype._resetVertexBufferBinding = function () {
  13196. this.bindArrayBuffer(null);
  13197. this._cachedVertexBuffers = null;
  13198. };
  13199. /**
  13200. * Creates a vertex buffer
  13201. * @param data the data for the vertex buffer
  13202. * @returns the new WebGL static buffer
  13203. */
  13204. Engine.prototype.createVertexBuffer = function (data) {
  13205. var vbo = this._gl.createBuffer();
  13206. if (!vbo) {
  13207. throw new Error("Unable to create vertex buffer");
  13208. }
  13209. this.bindArrayBuffer(vbo);
  13210. if (data instanceof Array) {
  13211. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13212. }
  13213. else {
  13214. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13215. }
  13216. this._resetVertexBufferBinding();
  13217. vbo.references = 1;
  13218. return vbo;
  13219. };
  13220. /**
  13221. * Creates a dynamic vertex buffer
  13222. * @param data the data for the dynamic vertex buffer
  13223. * @returns the new WebGL dynamic buffer
  13224. */
  13225. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13226. var vbo = this._gl.createBuffer();
  13227. if (!vbo) {
  13228. throw new Error("Unable to create dynamic vertex buffer");
  13229. }
  13230. this.bindArrayBuffer(vbo);
  13231. if (data instanceof Array) {
  13232. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13233. }
  13234. else {
  13235. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13236. }
  13237. this._resetVertexBufferBinding();
  13238. vbo.references = 1;
  13239. return vbo;
  13240. };
  13241. /**
  13242. * Update a dynamic index buffer
  13243. * @param indexBuffer defines the target index buffer
  13244. * @param indices defines the data to update
  13245. * @param offset defines the offset in the target index buffer where update should start
  13246. */
  13247. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13248. if (offset === void 0) { offset = 0; }
  13249. // Force cache update
  13250. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13251. this.bindIndexBuffer(indexBuffer);
  13252. var arrayBuffer;
  13253. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13254. arrayBuffer = indices;
  13255. }
  13256. else {
  13257. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13258. }
  13259. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13260. this._resetIndexBufferBinding();
  13261. };
  13262. /**
  13263. * Updates a dynamic vertex buffer.
  13264. * @param vertexBuffer the vertex buffer to update
  13265. * @param data the data used to update the vertex buffer
  13266. * @param byteOffset the byte offset of the data
  13267. * @param byteLength the byte length of the data
  13268. */
  13269. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13270. this.bindArrayBuffer(vertexBuffer);
  13271. if (byteOffset === undefined) {
  13272. byteOffset = 0;
  13273. }
  13274. if (byteLength === undefined) {
  13275. if (data instanceof Array) {
  13276. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13277. }
  13278. else {
  13279. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13280. }
  13281. }
  13282. else {
  13283. if (data instanceof Array) {
  13284. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13285. }
  13286. else {
  13287. if (data instanceof ArrayBuffer) {
  13288. data = new Uint8Array(data, byteOffset, byteLength);
  13289. }
  13290. else {
  13291. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13292. }
  13293. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13294. }
  13295. }
  13296. this._resetVertexBufferBinding();
  13297. };
  13298. Engine.prototype._resetIndexBufferBinding = function () {
  13299. this.bindIndexBuffer(null);
  13300. this._cachedIndexBuffer = null;
  13301. };
  13302. /**
  13303. * Creates a new index buffer
  13304. * @param indices defines the content of the index buffer
  13305. * @param updatable defines if the index buffer must be updatable
  13306. * @returns a new webGL buffer
  13307. */
  13308. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13309. var vbo = this._gl.createBuffer();
  13310. if (!vbo) {
  13311. throw new Error("Unable to create index buffer");
  13312. }
  13313. this.bindIndexBuffer(vbo);
  13314. // Check for 32 bits indices
  13315. var arrayBuffer;
  13316. var need32Bits = false;
  13317. if (indices instanceof Uint16Array) {
  13318. arrayBuffer = indices;
  13319. }
  13320. else {
  13321. //check 32 bit support
  13322. if (this._caps.uintIndices) {
  13323. if (indices instanceof Uint32Array) {
  13324. arrayBuffer = indices;
  13325. need32Bits = true;
  13326. }
  13327. else {
  13328. //number[] or Int32Array, check if 32 bit is necessary
  13329. for (var index = 0; index < indices.length; index++) {
  13330. if (indices[index] > 65535) {
  13331. need32Bits = true;
  13332. break;
  13333. }
  13334. }
  13335. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13336. }
  13337. }
  13338. else {
  13339. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13340. arrayBuffer = new Uint16Array(indices);
  13341. }
  13342. }
  13343. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13344. this._resetIndexBufferBinding();
  13345. vbo.references = 1;
  13346. vbo.is32Bits = need32Bits;
  13347. return vbo;
  13348. };
  13349. /**
  13350. * Bind a webGL buffer to the webGL context
  13351. * @param buffer defines the buffer to bind
  13352. */
  13353. Engine.prototype.bindArrayBuffer = function (buffer) {
  13354. if (!this._vaoRecordInProgress) {
  13355. this._unbindVertexArrayObject();
  13356. }
  13357. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13358. };
  13359. /**
  13360. * Bind an uniform buffer to the current webGL context
  13361. * @param buffer defines the buffer to bind
  13362. */
  13363. Engine.prototype.bindUniformBuffer = function (buffer) {
  13364. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13365. };
  13366. /**
  13367. * Bind a buffer to the current webGL context at a given location
  13368. * @param buffer defines the buffer to bind
  13369. * @param location defines the index where to bind the buffer
  13370. */
  13371. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13372. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13373. };
  13374. /**
  13375. * Bind a specific block at a given index in a specific shader program
  13376. * @param shaderProgram defines the shader program
  13377. * @param blockName defines the block name
  13378. * @param index defines the index where to bind the block
  13379. */
  13380. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13381. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13382. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13383. };
  13384. ;
  13385. Engine.prototype.bindIndexBuffer = function (buffer) {
  13386. if (!this._vaoRecordInProgress) {
  13387. this._unbindVertexArrayObject();
  13388. }
  13389. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13390. };
  13391. Engine.prototype.bindBuffer = function (buffer, target) {
  13392. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13393. this._gl.bindBuffer(target, buffer);
  13394. this._currentBoundBuffer[target] = buffer;
  13395. }
  13396. };
  13397. /**
  13398. * update the bound buffer with the given data
  13399. * @param data defines the data to update
  13400. */
  13401. Engine.prototype.updateArrayBuffer = function (data) {
  13402. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13403. };
  13404. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13405. var pointer = this._currentBufferPointers[indx];
  13406. var changed = false;
  13407. if (!pointer.active) {
  13408. changed = true;
  13409. pointer.active = true;
  13410. pointer.index = indx;
  13411. pointer.size = size;
  13412. pointer.type = type;
  13413. pointer.normalized = normalized;
  13414. pointer.stride = stride;
  13415. pointer.offset = offset;
  13416. pointer.buffer = buffer;
  13417. }
  13418. else {
  13419. if (pointer.buffer !== buffer) {
  13420. pointer.buffer = buffer;
  13421. changed = true;
  13422. }
  13423. if (pointer.size !== size) {
  13424. pointer.size = size;
  13425. changed = true;
  13426. }
  13427. if (pointer.type !== type) {
  13428. pointer.type = type;
  13429. changed = true;
  13430. }
  13431. if (pointer.normalized !== normalized) {
  13432. pointer.normalized = normalized;
  13433. changed = true;
  13434. }
  13435. if (pointer.stride !== stride) {
  13436. pointer.stride = stride;
  13437. changed = true;
  13438. }
  13439. if (pointer.offset !== offset) {
  13440. pointer.offset = offset;
  13441. changed = true;
  13442. }
  13443. }
  13444. if (changed || this._vaoRecordInProgress) {
  13445. this.bindArrayBuffer(buffer);
  13446. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13447. }
  13448. };
  13449. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13450. if (indexBuffer == null) {
  13451. return;
  13452. }
  13453. if (this._cachedIndexBuffer !== indexBuffer) {
  13454. this._cachedIndexBuffer = indexBuffer;
  13455. this.bindIndexBuffer(indexBuffer);
  13456. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13457. }
  13458. };
  13459. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13460. var attributes = effect.getAttributesNames();
  13461. if (!this._vaoRecordInProgress) {
  13462. this._unbindVertexArrayObject();
  13463. }
  13464. this.unbindAllAttributes();
  13465. for (var index = 0; index < attributes.length; index++) {
  13466. var order = effect.getAttributeLocation(index);
  13467. if (order >= 0) {
  13468. var vertexBuffer = vertexBuffers[attributes[index]];
  13469. if (!vertexBuffer) {
  13470. continue;
  13471. }
  13472. this._gl.enableVertexAttribArray(order);
  13473. if (!this._vaoRecordInProgress) {
  13474. this._vertexAttribArraysEnabled[order] = true;
  13475. }
  13476. var buffer = vertexBuffer.getBuffer();
  13477. if (buffer) {
  13478. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13479. if (vertexBuffer.getIsInstanced()) {
  13480. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13481. if (!this._vaoRecordInProgress) {
  13482. this._currentInstanceLocations.push(order);
  13483. this._currentInstanceBuffers.push(buffer);
  13484. }
  13485. }
  13486. }
  13487. }
  13488. }
  13489. };
  13490. /**
  13491. * Records a vertex array object
  13492. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13493. * @param vertexBuffers defines the list of vertex buffers to store
  13494. * @param indexBuffer defines the index buffer to store
  13495. * @param effect defines the effect to store
  13496. * @returns the new vertex array object
  13497. */
  13498. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13499. var vao = this._gl.createVertexArray();
  13500. this._vaoRecordInProgress = true;
  13501. this._gl.bindVertexArray(vao);
  13502. this._mustWipeVertexAttributes = true;
  13503. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13504. this.bindIndexBuffer(indexBuffer);
  13505. this._vaoRecordInProgress = false;
  13506. this._gl.bindVertexArray(null);
  13507. return vao;
  13508. };
  13509. /**
  13510. * Bind a specific vertex array object
  13511. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13512. * @param vertexArrayObject defines the vertex array object to bind
  13513. * @param indexBuffer defines the index buffer to bind
  13514. */
  13515. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13516. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13517. this._cachedVertexArrayObject = vertexArrayObject;
  13518. this._gl.bindVertexArray(vertexArrayObject);
  13519. this._cachedVertexBuffers = null;
  13520. this._cachedIndexBuffer = null;
  13521. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13522. this._mustWipeVertexAttributes = true;
  13523. }
  13524. };
  13525. /**
  13526. * Bind webGl buffers directly to the webGL context
  13527. * @param vertexBuffer defines the vertex buffer to bind
  13528. * @param indexBuffer defines the index buffer to bind
  13529. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13530. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13531. * @param effect defines the effect associated with the vertex buffer
  13532. */
  13533. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13534. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13535. this._cachedVertexBuffers = vertexBuffer;
  13536. this._cachedEffectForVertexBuffers = effect;
  13537. var attributesCount = effect.getAttributesCount();
  13538. this._unbindVertexArrayObject();
  13539. this.unbindAllAttributes();
  13540. var offset = 0;
  13541. for (var index = 0; index < attributesCount; index++) {
  13542. if (index < vertexDeclaration.length) {
  13543. var order = effect.getAttributeLocation(index);
  13544. if (order >= 0) {
  13545. this._gl.enableVertexAttribArray(order);
  13546. this._vertexAttribArraysEnabled[order] = true;
  13547. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13548. }
  13549. offset += vertexDeclaration[index] * 4;
  13550. }
  13551. }
  13552. }
  13553. this._bindIndexBufferWithCache(indexBuffer);
  13554. };
  13555. Engine.prototype._unbindVertexArrayObject = function () {
  13556. if (!this._cachedVertexArrayObject) {
  13557. return;
  13558. }
  13559. this._cachedVertexArrayObject = null;
  13560. this._gl.bindVertexArray(null);
  13561. };
  13562. /**
  13563. * Bind a list of vertex buffers to the webGL context
  13564. * @param vertexBuffers defines the list of vertex buffers to bind
  13565. * @param indexBuffer defines the index buffer to bind
  13566. * @param effect defines the effect associated with the vertex buffers
  13567. */
  13568. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13569. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13570. this._cachedVertexBuffers = vertexBuffers;
  13571. this._cachedEffectForVertexBuffers = effect;
  13572. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13573. }
  13574. this._bindIndexBufferWithCache(indexBuffer);
  13575. };
  13576. /**
  13577. * Unbind all instance attributes
  13578. */
  13579. Engine.prototype.unbindInstanceAttributes = function () {
  13580. var boundBuffer;
  13581. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13582. var instancesBuffer = this._currentInstanceBuffers[i];
  13583. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13584. boundBuffer = instancesBuffer;
  13585. this.bindArrayBuffer(instancesBuffer);
  13586. }
  13587. var offsetLocation = this._currentInstanceLocations[i];
  13588. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13589. }
  13590. this._currentInstanceBuffers.length = 0;
  13591. this._currentInstanceLocations.length = 0;
  13592. };
  13593. /**
  13594. * Release and free the memory of a vertex array object
  13595. * @param vao defines the vertex array object to delete
  13596. */
  13597. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13598. this._gl.deleteVertexArray(vao);
  13599. };
  13600. /** @hidden */
  13601. Engine.prototype._releaseBuffer = function (buffer) {
  13602. buffer.references--;
  13603. if (buffer.references === 0) {
  13604. this._gl.deleteBuffer(buffer);
  13605. return true;
  13606. }
  13607. return false;
  13608. };
  13609. /**
  13610. * Creates a webGL buffer to use with instanciation
  13611. * @param capacity defines the size of the buffer
  13612. * @returns the webGL buffer
  13613. */
  13614. Engine.prototype.createInstancesBuffer = function (capacity) {
  13615. var buffer = this._gl.createBuffer();
  13616. if (!buffer) {
  13617. throw new Error("Unable to create instance buffer");
  13618. }
  13619. buffer.capacity = capacity;
  13620. this.bindArrayBuffer(buffer);
  13621. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13622. return buffer;
  13623. };
  13624. /**
  13625. * Delete a webGL buffer used with instanciation
  13626. * @param buffer defines the webGL buffer to delete
  13627. */
  13628. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13629. this._gl.deleteBuffer(buffer);
  13630. };
  13631. /**
  13632. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13633. * @param instancesBuffer defines the webGL buffer to update and bind
  13634. * @param data defines the data to store in the buffer
  13635. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13636. */
  13637. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13638. this.bindArrayBuffer(instancesBuffer);
  13639. if (data) {
  13640. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13641. }
  13642. if (offsetLocations[0].index !== undefined) {
  13643. var stride = 0;
  13644. for (var i = 0; i < offsetLocations.length; i++) {
  13645. var ai = offsetLocations[i];
  13646. stride += ai.attributeSize * 4;
  13647. }
  13648. for (var i = 0; i < offsetLocations.length; i++) {
  13649. var ai = offsetLocations[i];
  13650. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13651. this._gl.enableVertexAttribArray(ai.index);
  13652. this._vertexAttribArraysEnabled[ai.index] = true;
  13653. }
  13654. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13655. this._gl.vertexAttribDivisor(ai.index, 1);
  13656. this._currentInstanceLocations.push(ai.index);
  13657. this._currentInstanceBuffers.push(instancesBuffer);
  13658. }
  13659. }
  13660. else {
  13661. for (var index = 0; index < 4; index++) {
  13662. var offsetLocation = offsetLocations[index];
  13663. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13664. this._gl.enableVertexAttribArray(offsetLocation);
  13665. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13666. }
  13667. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13668. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13669. this._currentInstanceLocations.push(offsetLocation);
  13670. this._currentInstanceBuffers.push(instancesBuffer);
  13671. }
  13672. }
  13673. };
  13674. /**
  13675. * Apply all cached states (depth, culling, stencil and alpha)
  13676. */
  13677. Engine.prototype.applyStates = function () {
  13678. this._depthCullingState.apply(this._gl);
  13679. this._stencilState.apply(this._gl);
  13680. this._alphaState.apply(this._gl);
  13681. };
  13682. /**
  13683. * Send a draw order
  13684. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13685. * @param indexStart defines the starting index
  13686. * @param indexCount defines the number of index to draw
  13687. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13688. */
  13689. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13690. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13691. };
  13692. /**
  13693. * Draw a list of points
  13694. * @param verticesStart defines the index of first vertex to draw
  13695. * @param verticesCount defines the count of vertices to draw
  13696. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13697. */
  13698. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13699. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13700. };
  13701. /**
  13702. * Draw a list of unindexed primitives
  13703. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13704. * @param verticesStart defines the index of first vertex to draw
  13705. * @param verticesCount defines the count of vertices to draw
  13706. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13707. */
  13708. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13709. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13710. };
  13711. /**
  13712. * Draw a list of indexed primitives
  13713. * @param fillMode defines the primitive to use
  13714. * @param indexStart defines the starting index
  13715. * @param indexCount defines the number of index to draw
  13716. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13717. */
  13718. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13719. // Apply states
  13720. this.applyStates();
  13721. this._drawCalls.addCount(1, false);
  13722. // Render
  13723. var drawMode = this._drawMode(fillMode);
  13724. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13725. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13726. if (instancesCount) {
  13727. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13728. }
  13729. else {
  13730. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13731. }
  13732. };
  13733. /**
  13734. * Draw a list of unindexed primitives
  13735. * @param fillMode defines the primitive to use
  13736. * @param verticesStart defines the index of first vertex to draw
  13737. * @param verticesCount defines the count of vertices to draw
  13738. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13739. */
  13740. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13741. // Apply states
  13742. this.applyStates();
  13743. this._drawCalls.addCount(1, false);
  13744. var drawMode = this._drawMode(fillMode);
  13745. if (instancesCount) {
  13746. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13747. }
  13748. else {
  13749. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13750. }
  13751. };
  13752. Engine.prototype._drawMode = function (fillMode) {
  13753. switch (fillMode) {
  13754. // Triangle views
  13755. case BABYLON.Material.TriangleFillMode:
  13756. return this._gl.TRIANGLES;
  13757. case BABYLON.Material.PointFillMode:
  13758. return this._gl.POINTS;
  13759. case BABYLON.Material.WireFrameFillMode:
  13760. return this._gl.LINES;
  13761. // Draw modes
  13762. case BABYLON.Material.PointListDrawMode:
  13763. return this._gl.POINTS;
  13764. case BABYLON.Material.LineListDrawMode:
  13765. return this._gl.LINES;
  13766. case BABYLON.Material.LineLoopDrawMode:
  13767. return this._gl.LINE_LOOP;
  13768. case BABYLON.Material.LineStripDrawMode:
  13769. return this._gl.LINE_STRIP;
  13770. case BABYLON.Material.TriangleStripDrawMode:
  13771. return this._gl.TRIANGLE_STRIP;
  13772. case BABYLON.Material.TriangleFanDrawMode:
  13773. return this._gl.TRIANGLE_FAN;
  13774. default:
  13775. return this._gl.TRIANGLES;
  13776. }
  13777. };
  13778. // Shaders
  13779. /** @hidden */
  13780. Engine.prototype._releaseEffect = function (effect) {
  13781. if (this._compiledEffects[effect._key]) {
  13782. delete this._compiledEffects[effect._key];
  13783. this._deleteProgram(effect.getProgram());
  13784. }
  13785. };
  13786. /** @hidden */
  13787. Engine.prototype._deleteProgram = function (program) {
  13788. if (program) {
  13789. program.__SPECTOR_rebuildProgram = null;
  13790. if (program.transformFeedback) {
  13791. this.deleteTransformFeedback(program.transformFeedback);
  13792. program.transformFeedback = null;
  13793. }
  13794. this._gl.deleteProgram(program);
  13795. }
  13796. };
  13797. /**
  13798. * Create a new effect (used to store vertex/fragment shaders)
  13799. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13800. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13801. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13802. * @param samplers defines an array of string used to represent textures
  13803. * @param defines defines the string containing the defines to use to compile the shaders
  13804. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13805. * @param onCompiled defines a function to call when the effect creation is successful
  13806. * @param onError defines a function to call when the effect creation has failed
  13807. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13808. * @returns the new Effect
  13809. */
  13810. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13811. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13812. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13813. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13814. if (this._compiledEffects[name]) {
  13815. var compiledEffect = this._compiledEffects[name];
  13816. if (onCompiled && compiledEffect.isReady()) {
  13817. onCompiled(compiledEffect);
  13818. }
  13819. return compiledEffect;
  13820. }
  13821. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13822. effect._key = name;
  13823. this._compiledEffects[name] = effect;
  13824. return effect;
  13825. };
  13826. /**
  13827. * Create an effect to use with particle systems
  13828. * @param fragmentName defines the base name of the effect (The name of file without .fragment.fx)
  13829. * @param uniformsNames defines a list of attribute names
  13830. * @param samplers defines an array of string used to represent textures
  13831. * @param defines defines the string containing the defines to use to compile the shaders
  13832. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13833. * @param onCompiled defines a function to call when the effect creation is successful
  13834. * @param onError defines a function to call when the effect creation has failed
  13835. * @returns the new Effect
  13836. */
  13837. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  13838. if (uniformsNames === void 0) { uniformsNames = []; }
  13839. if (samplers === void 0) { samplers = []; }
  13840. if (defines === void 0) { defines = ""; }
  13841. return this.createEffect({
  13842. vertex: "particles",
  13843. fragmentElement: fragmentName
  13844. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  13845. };
  13846. /**
  13847. * Directly creates a webGL program
  13848. * @param vertexCode defines the vertex shader code to use
  13849. * @param fragmentCode defines the fragment shader code to use
  13850. * @param context defines the webGL context to use (if not set, the current one will be used)
  13851. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13852. * @returns the new webGL program
  13853. */
  13854. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  13855. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13856. context = context || this._gl;
  13857. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  13858. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  13859. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13860. };
  13861. /**
  13862. * Creates a webGL program
  13863. * @param vertexCode defines the vertex shader code to use
  13864. * @param fragmentCode defines the fragment shader code to use
  13865. * @param defines defines the string containing the defines to use to compile the shaders
  13866. * @param context defines the webGL context to use (if not set, the current one will be used)
  13867. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13868. * @returns the new webGL program
  13869. */
  13870. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  13871. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13872. context = context || this._gl;
  13873. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  13874. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  13875. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  13876. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  13877. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13878. this.onAfterShaderCompilationObservable.notifyObservers(this);
  13879. return program;
  13880. };
  13881. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  13882. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13883. var shaderProgram = context.createProgram();
  13884. if (!shaderProgram) {
  13885. throw new Error("Unable to create program");
  13886. }
  13887. context.attachShader(shaderProgram, vertexShader);
  13888. context.attachShader(shaderProgram, fragmentShader);
  13889. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13890. var transformFeedback = this.createTransformFeedback();
  13891. this.bindTransformFeedback(transformFeedback);
  13892. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  13893. shaderProgram.transformFeedback = transformFeedback;
  13894. }
  13895. context.linkProgram(shaderProgram);
  13896. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13897. this.bindTransformFeedback(null);
  13898. }
  13899. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  13900. if (!linked) {
  13901. context.validateProgram(shaderProgram);
  13902. var error = context.getProgramInfoLog(shaderProgram);
  13903. if (error) {
  13904. throw new Error(error);
  13905. }
  13906. }
  13907. context.deleteShader(vertexShader);
  13908. context.deleteShader(fragmentShader);
  13909. return shaderProgram;
  13910. };
  13911. /**
  13912. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  13913. * @param shaderProgram defines the webGL program to use
  13914. * @param uniformsNames defines the list of uniform names
  13915. * @returns an array of webGL uniform locations
  13916. */
  13917. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  13918. var results = new Array();
  13919. for (var index = 0; index < uniformsNames.length; index++) {
  13920. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  13921. }
  13922. return results;
  13923. };
  13924. /**
  13925. * Gets the lsit of active attributes for a given webGL program
  13926. * @param shaderProgram defines the webGL program to use
  13927. * @param attributesNames defines the list of attribute names to get
  13928. * @returns an array of indices indicating the offset of each attribute
  13929. */
  13930. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  13931. var results = [];
  13932. for (var index = 0; index < attributesNames.length; index++) {
  13933. try {
  13934. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  13935. }
  13936. catch (e) {
  13937. results.push(-1);
  13938. }
  13939. }
  13940. return results;
  13941. };
  13942. /**
  13943. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  13944. * @param effect defines the effect to activate
  13945. */
  13946. Engine.prototype.enableEffect = function (effect) {
  13947. if (!effect) {
  13948. return;
  13949. }
  13950. // Use program
  13951. this.bindSamplers(effect);
  13952. this._currentEffect = effect;
  13953. if (effect.onBind) {
  13954. effect.onBind(effect);
  13955. }
  13956. effect.onBindObservable.notifyObservers(effect);
  13957. };
  13958. /**
  13959. * Set the value of an uniform to an array of int32
  13960. * @param uniform defines the webGL uniform location where to store the value
  13961. * @param array defines the array of int32 to store
  13962. */
  13963. Engine.prototype.setIntArray = function (uniform, array) {
  13964. if (!uniform)
  13965. return;
  13966. this._gl.uniform1iv(uniform, array);
  13967. };
  13968. /**
  13969. * Set the value of an uniform to an array of int32 (stored as vec2)
  13970. * @param uniform defines the webGL uniform location where to store the value
  13971. * @param array defines the array of int32 to store
  13972. */
  13973. Engine.prototype.setIntArray2 = function (uniform, array) {
  13974. if (!uniform || array.length % 2 !== 0)
  13975. return;
  13976. this._gl.uniform2iv(uniform, array);
  13977. };
  13978. /**
  13979. * Set the value of an uniform to an array of int32 (stored as vec3)
  13980. * @param uniform defines the webGL uniform location where to store the value
  13981. * @param array defines the array of int32 to store
  13982. */
  13983. Engine.prototype.setIntArray3 = function (uniform, array) {
  13984. if (!uniform || array.length % 3 !== 0)
  13985. return;
  13986. this._gl.uniform3iv(uniform, array);
  13987. };
  13988. /**
  13989. * Set the value of an uniform to an array of int32 (stored as vec4)
  13990. * @param uniform defines the webGL uniform location where to store the value
  13991. * @param array defines the array of int32 to store
  13992. */
  13993. Engine.prototype.setIntArray4 = function (uniform, array) {
  13994. if (!uniform || array.length % 4 !== 0)
  13995. return;
  13996. this._gl.uniform4iv(uniform, array);
  13997. };
  13998. /**
  13999. * Set the value of an uniform to an array of float32
  14000. * @param uniform defines the webGL uniform location where to store the value
  14001. * @param array defines the array of float32 to store
  14002. */
  14003. Engine.prototype.setFloatArray = function (uniform, array) {
  14004. if (!uniform)
  14005. return;
  14006. this._gl.uniform1fv(uniform, array);
  14007. };
  14008. /**
  14009. * Set the value of an uniform to an array of float32 (stored as vec2)
  14010. * @param uniform defines the webGL uniform location where to store the value
  14011. * @param array defines the array of float32 to store
  14012. */
  14013. Engine.prototype.setFloatArray2 = function (uniform, array) {
  14014. if (!uniform || array.length % 2 !== 0)
  14015. return;
  14016. this._gl.uniform2fv(uniform, array);
  14017. };
  14018. /**
  14019. * Set the value of an uniform to an array of float32 (stored as vec3)
  14020. * @param uniform defines the webGL uniform location where to store the value
  14021. * @param array defines the array of float32 to store
  14022. */
  14023. Engine.prototype.setFloatArray3 = function (uniform, array) {
  14024. if (!uniform || array.length % 3 !== 0)
  14025. return;
  14026. this._gl.uniform3fv(uniform, array);
  14027. };
  14028. /**
  14029. * Set the value of an uniform to an array of float32 (stored as vec4)
  14030. * @param uniform defines the webGL uniform location where to store the value
  14031. * @param array defines the array of float32 to store
  14032. */
  14033. Engine.prototype.setFloatArray4 = function (uniform, array) {
  14034. if (!uniform || array.length % 4 !== 0)
  14035. return;
  14036. this._gl.uniform4fv(uniform, array);
  14037. };
  14038. /**
  14039. * Set the value of an uniform to an array of number
  14040. * @param uniform defines the webGL uniform location where to store the value
  14041. * @param array defines the array of number to store
  14042. */
  14043. Engine.prototype.setArray = function (uniform, array) {
  14044. if (!uniform)
  14045. return;
  14046. this._gl.uniform1fv(uniform, array);
  14047. };
  14048. /**
  14049. * Set the value of an uniform to an array of number (stored as vec2)
  14050. * @param uniform defines the webGL uniform location where to store the value
  14051. * @param array defines the array of number to store
  14052. */
  14053. Engine.prototype.setArray2 = function (uniform, array) {
  14054. if (!uniform || array.length % 2 !== 0)
  14055. return;
  14056. this._gl.uniform2fv(uniform, array);
  14057. };
  14058. /**
  14059. * Set the value of an uniform to an array of number (stored as vec3)
  14060. * @param uniform defines the webGL uniform location where to store the value
  14061. * @param array defines the array of number to store
  14062. */
  14063. Engine.prototype.setArray3 = function (uniform, array) {
  14064. if (!uniform || array.length % 3 !== 0)
  14065. return;
  14066. this._gl.uniform3fv(uniform, array);
  14067. };
  14068. /**
  14069. * Set the value of an uniform to an array of number (stored as vec4)
  14070. * @param uniform defines the webGL uniform location where to store the value
  14071. * @param array defines the array of number to store
  14072. */
  14073. Engine.prototype.setArray4 = function (uniform, array) {
  14074. if (!uniform || array.length % 4 !== 0)
  14075. return;
  14076. this._gl.uniform4fv(uniform, array);
  14077. };
  14078. /**
  14079. * Set the value of an uniform to an array of float32 (stored as matrices)
  14080. * @param uniform defines the webGL uniform location where to store the value
  14081. * @param matrices defines the array of float32 to store
  14082. */
  14083. Engine.prototype.setMatrices = function (uniform, matrices) {
  14084. if (!uniform)
  14085. return;
  14086. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14087. };
  14088. /**
  14089. * Set the value of an uniform to a matrix
  14090. * @param uniform defines the webGL uniform location where to store the value
  14091. * @param matrix defines the matrix to store
  14092. */
  14093. Engine.prototype.setMatrix = function (uniform, matrix) {
  14094. if (!uniform)
  14095. return;
  14096. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14097. };
  14098. /**
  14099. * Set the value of an uniform to a matrix (3x3)
  14100. * @param uniform defines the webGL uniform location where to store the value
  14101. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14102. */
  14103. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14104. if (!uniform)
  14105. return;
  14106. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14107. };
  14108. /**
  14109. * Set the value of an uniform to a matrix (2x2)
  14110. * @param uniform defines the webGL uniform location where to store the value
  14111. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14112. */
  14113. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14114. if (!uniform)
  14115. return;
  14116. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14117. };
  14118. /**
  14119. * Set the value of an uniform to a number (int)
  14120. * @param uniform defines the webGL uniform location where to store the value
  14121. * @param value defines the int number to store
  14122. */
  14123. Engine.prototype.setInt = function (uniform, value) {
  14124. if (!uniform)
  14125. return;
  14126. this._gl.uniform1i(uniform, value);
  14127. };
  14128. /**
  14129. * Set the value of an uniform to a number (float)
  14130. * @param uniform defines the webGL uniform location where to store the value
  14131. * @param value defines the float number to store
  14132. */
  14133. Engine.prototype.setFloat = function (uniform, value) {
  14134. if (!uniform)
  14135. return;
  14136. this._gl.uniform1f(uniform, value);
  14137. };
  14138. /**
  14139. * Set the value of an uniform to a vec2
  14140. * @param uniform defines the webGL uniform location where to store the value
  14141. * @param x defines the 1st component of the value
  14142. * @param y defines the 2nd component of the value
  14143. */
  14144. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14145. if (!uniform)
  14146. return;
  14147. this._gl.uniform2f(uniform, x, y);
  14148. };
  14149. /**
  14150. * Set the value of an uniform to a vec3
  14151. * @param uniform defines the webGL uniform location where to store the value
  14152. * @param x defines the 1st component of the value
  14153. * @param y defines the 2nd component of the value
  14154. * @param z defines the 3rd component of the value
  14155. */
  14156. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14157. if (!uniform)
  14158. return;
  14159. this._gl.uniform3f(uniform, x, y, z);
  14160. };
  14161. /**
  14162. * Set the value of an uniform to a boolean
  14163. * @param uniform defines the webGL uniform location where to store the value
  14164. * @param bool defines the boolean to store
  14165. */
  14166. Engine.prototype.setBool = function (uniform, bool) {
  14167. if (!uniform)
  14168. return;
  14169. this._gl.uniform1i(uniform, bool);
  14170. };
  14171. /**
  14172. * Set the value of an uniform to a vec4
  14173. * @param uniform defines the webGL uniform location where to store the value
  14174. * @param x defines the 1st component of the value
  14175. * @param y defines the 2nd component of the value
  14176. * @param z defines the 3rd component of the value
  14177. * @param w defines the 4th component of the value
  14178. */
  14179. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14180. if (!uniform)
  14181. return;
  14182. this._gl.uniform4f(uniform, x, y, z, w);
  14183. };
  14184. /**
  14185. * Set the value of an uniform to a Color3
  14186. * @param uniform defines the webGL uniform location where to store the value
  14187. * @param color3 defines the color to store
  14188. */
  14189. Engine.prototype.setColor3 = function (uniform, color3) {
  14190. if (!uniform)
  14191. return;
  14192. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14193. };
  14194. /**
  14195. * Set the value of an uniform to a Color3 and an alpha value
  14196. * @param uniform defines the webGL uniform location where to store the value
  14197. * @param color3 defines the color to store
  14198. * @param alpha defines the alpha component to store
  14199. */
  14200. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14201. if (!uniform)
  14202. return;
  14203. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14204. };
  14205. /**
  14206. * Sets a Color4 on a uniform variable
  14207. * @param uniform defines the uniform location
  14208. * @param color4 defines the value to be set
  14209. */
  14210. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14211. if (!uniform)
  14212. return;
  14213. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14214. };
  14215. // States
  14216. /**
  14217. * Set various states to the webGL context
  14218. * @param culling defines backface culling state
  14219. * @param zOffset defines the value to apply to zOffset (0 by default)
  14220. * @param force defines if states must be applied even if cache is up to date
  14221. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14222. */
  14223. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14224. if (zOffset === void 0) { zOffset = 0; }
  14225. if (reverseSide === void 0) { reverseSide = false; }
  14226. // Culling
  14227. if (this._depthCullingState.cull !== culling || force) {
  14228. this._depthCullingState.cull = culling;
  14229. }
  14230. // Cull face
  14231. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14232. if (this._depthCullingState.cullFace !== cullFace || force) {
  14233. this._depthCullingState.cullFace = cullFace;
  14234. }
  14235. // Z offset
  14236. this.setZOffset(zOffset);
  14237. // Front face
  14238. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14239. if (this._depthCullingState.frontFace !== frontFace || force) {
  14240. this._depthCullingState.frontFace = frontFace;
  14241. }
  14242. };
  14243. /**
  14244. * Set the z offset to apply to current rendering
  14245. * @param value defines the offset to apply
  14246. */
  14247. Engine.prototype.setZOffset = function (value) {
  14248. this._depthCullingState.zOffset = value;
  14249. };
  14250. /**
  14251. * Gets the current value of the zOffset
  14252. * @returns the current zOffset state
  14253. */
  14254. Engine.prototype.getZOffset = function () {
  14255. return this._depthCullingState.zOffset;
  14256. };
  14257. /**
  14258. * Enable or disable depth buffering
  14259. * @param enable defines the state to set
  14260. */
  14261. Engine.prototype.setDepthBuffer = function (enable) {
  14262. this._depthCullingState.depthTest = enable;
  14263. };
  14264. /**
  14265. * Gets a boolean indicating if depth writing is enabled
  14266. * @returns the current depth writing state
  14267. */
  14268. Engine.prototype.getDepthWrite = function () {
  14269. return this._depthCullingState.depthMask;
  14270. };
  14271. /**
  14272. * Enable or disable depth writing
  14273. * @param enable defines the state to set
  14274. */
  14275. Engine.prototype.setDepthWrite = function (enable) {
  14276. this._depthCullingState.depthMask = enable;
  14277. };
  14278. /**
  14279. * Enable or disable color writing
  14280. * @param enable defines the state to set
  14281. */
  14282. Engine.prototype.setColorWrite = function (enable) {
  14283. this._gl.colorMask(enable, enable, enable, enable);
  14284. this._colorWrite = enable;
  14285. };
  14286. /**
  14287. * Gets a boolean indicating if color writing is enabled
  14288. * @returns the current color writing state
  14289. */
  14290. Engine.prototype.getColorWrite = function () {
  14291. return this._colorWrite;
  14292. };
  14293. /**
  14294. * Sets alpha constants used by some alpha blending modes
  14295. * @param r defines the red component
  14296. * @param g defines the green component
  14297. * @param b defines the blue component
  14298. * @param a defines the alpha component
  14299. */
  14300. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14301. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14302. };
  14303. /**
  14304. * Sets the current alpha mode
  14305. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14306. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14307. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14308. */
  14309. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14310. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14311. if (this._alphaMode === mode) {
  14312. return;
  14313. }
  14314. switch (mode) {
  14315. case Engine.ALPHA_DISABLE:
  14316. this._alphaState.alphaBlend = false;
  14317. break;
  14318. case Engine.ALPHA_PREMULTIPLIED:
  14319. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14320. this._alphaState.alphaBlend = true;
  14321. break;
  14322. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14323. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14324. this._alphaState.alphaBlend = true;
  14325. break;
  14326. case Engine.ALPHA_COMBINE:
  14327. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14328. this._alphaState.alphaBlend = true;
  14329. break;
  14330. case Engine.ALPHA_ONEONE:
  14331. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14332. this._alphaState.alphaBlend = true;
  14333. break;
  14334. case Engine.ALPHA_ADD:
  14335. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14336. this._alphaState.alphaBlend = true;
  14337. break;
  14338. case Engine.ALPHA_SUBTRACT:
  14339. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14340. this._alphaState.alphaBlend = true;
  14341. break;
  14342. case Engine.ALPHA_MULTIPLY:
  14343. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14344. this._alphaState.alphaBlend = true;
  14345. break;
  14346. case Engine.ALPHA_MAXIMIZED:
  14347. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14348. this._alphaState.alphaBlend = true;
  14349. break;
  14350. case Engine.ALPHA_INTERPOLATE:
  14351. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14352. this._alphaState.alphaBlend = true;
  14353. break;
  14354. case Engine.ALPHA_SCREENMODE:
  14355. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14356. this._alphaState.alphaBlend = true;
  14357. break;
  14358. }
  14359. if (!noDepthWriteChange) {
  14360. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14361. }
  14362. this._alphaMode = mode;
  14363. };
  14364. /**
  14365. * Gets the current alpha mode
  14366. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14367. * @returns the current alpha mode
  14368. */
  14369. Engine.prototype.getAlphaMode = function () {
  14370. return this._alphaMode;
  14371. };
  14372. // Textures
  14373. /**
  14374. * Force the entire cache to be cleared
  14375. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14376. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14377. */
  14378. Engine.prototype.wipeCaches = function (bruteForce) {
  14379. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14380. return;
  14381. }
  14382. this._currentEffect = null;
  14383. if (bruteForce) {
  14384. this.resetTextureCache();
  14385. this._currentProgram = null;
  14386. this._stencilState.reset();
  14387. this._depthCullingState.reset();
  14388. this.setDepthFunctionToLessOrEqual();
  14389. this._alphaState.reset();
  14390. }
  14391. this._resetVertexBufferBinding();
  14392. this._cachedIndexBuffer = null;
  14393. this._cachedEffectForVertexBuffers = null;
  14394. this._unbindVertexArrayObject();
  14395. this.bindIndexBuffer(null);
  14396. };
  14397. /**
  14398. * Set the compressed texture format to use, based on the formats you have, and the formats
  14399. * supported by the hardware / browser.
  14400. *
  14401. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14402. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14403. * to API arguments needed to compressed textures. This puts the burden on the container
  14404. * generator to house the arcane code for determining these for current & future formats.
  14405. *
  14406. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14407. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14408. *
  14409. * Note: The result of this call is not taken into account when a texture is base64.
  14410. *
  14411. * @param formatsAvailable defines the list of those format families you have created
  14412. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14413. *
  14414. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14415. * @returns The extension selected.
  14416. */
  14417. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14418. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14419. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14420. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14421. return this._textureFormatInUse = this._texturesSupported[i];
  14422. }
  14423. }
  14424. }
  14425. // actively set format to nothing, to allow this to be called more than once
  14426. // and possibly fail the 2nd time
  14427. this._textureFormatInUse = null;
  14428. return null;
  14429. };
  14430. /** @hidden */
  14431. Engine.prototype._createTexture = function () {
  14432. var texture = this._gl.createTexture();
  14433. if (!texture) {
  14434. throw new Error("Unable to create texture");
  14435. }
  14436. return texture;
  14437. };
  14438. /**
  14439. * Usually called from BABYLON.Texture.ts.
  14440. * Passed information to create a WebGLTexture
  14441. * @param urlArg defines a value which contains one of the following:
  14442. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14443. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14444. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14445. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14446. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14447. * @param scene needed for loading to the correct scene
  14448. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14449. * @param onLoad optional callback to be called upon successful completion
  14450. * @param onError optional callback to be called upon failure
  14451. * @param buffer a source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  14452. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14453. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14454. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14455. */
  14456. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format) {
  14457. var _this = this;
  14458. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14459. if (onLoad === void 0) { onLoad = null; }
  14460. if (onError === void 0) { onError = null; }
  14461. if (buffer === void 0) { buffer = null; }
  14462. if (fallback === void 0) { fallback = null; }
  14463. if (format === void 0) { format = null; }
  14464. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14465. var fromData = url.substr(0, 5) === "data:";
  14466. var fromBlob = url.substr(0, 5) === "blob:";
  14467. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14468. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14469. // establish the file extension, if possible
  14470. var lastDot = url.lastIndexOf('.');
  14471. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  14472. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  14473. var isTGA = (extension.indexOf(".tga") === 0);
  14474. // determine if a ktx file should be substituted
  14475. var isKTX = false;
  14476. if (this._textureFormatInUse && !isBase64 && !fallback) {
  14477. url = url.substring(0, lastDot) + this._textureFormatInUse;
  14478. isKTX = true;
  14479. }
  14480. if (scene) {
  14481. scene._addPendingData(texture);
  14482. }
  14483. texture.url = url;
  14484. texture.generateMipMaps = !noMipmap;
  14485. texture.samplingMode = samplingMode;
  14486. texture.invertY = invertY;
  14487. if (!this._doNotHandleContextLost) {
  14488. // Keep a link to the buffer only if we plan to handle context lost
  14489. texture._buffer = buffer;
  14490. }
  14491. var onLoadObserver = null;
  14492. if (onLoad && !fallback) {
  14493. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14494. }
  14495. if (!fallback)
  14496. this._internalTexturesCache.push(texture);
  14497. var onerror = function (message, exception) {
  14498. if (scene) {
  14499. scene._removePendingData(texture);
  14500. }
  14501. if (onLoadObserver) {
  14502. texture.onLoadedObservable.remove(onLoadObserver);
  14503. }
  14504. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  14505. if (isKTX) {
  14506. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14507. }
  14508. else if (BABYLON.Tools.UseFallbackTexture) {
  14509. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14510. }
  14511. if (onError) {
  14512. onError(message || "Unknown error", exception);
  14513. }
  14514. };
  14515. var callback = null;
  14516. // processing for non-image formats
  14517. if (isKTX || isTGA || isDDS) {
  14518. if (isKTX) {
  14519. callback = function (data) {
  14520. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  14521. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  14522. ktx.uploadLevels(_this._gl, !noMipmap);
  14523. return false;
  14524. }, samplingMode);
  14525. };
  14526. }
  14527. else if (isTGA) {
  14528. callback = function (arrayBuffer) {
  14529. var data = new Uint8Array(arrayBuffer);
  14530. var header = BABYLON.TGATools.GetTGAHeader(data);
  14531. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  14532. BABYLON.TGATools.UploadContent(_this._gl, data);
  14533. return false;
  14534. }, samplingMode);
  14535. };
  14536. }
  14537. else if (isDDS) {
  14538. callback = function (data) {
  14539. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14540. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  14541. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  14542. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  14543. return false;
  14544. }, samplingMode);
  14545. };
  14546. }
  14547. if (!buffer) {
  14548. this._loadFile(url, function (data) {
  14549. if (callback) {
  14550. callback(data);
  14551. }
  14552. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14553. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  14554. });
  14555. }
  14556. else {
  14557. if (callback) {
  14558. callback(buffer);
  14559. }
  14560. }
  14561. // image format processing
  14562. }
  14563. else {
  14564. var onload = function (img) {
  14565. if (fromBlob && !_this._doNotHandleContextLost) {
  14566. // We need to store the image if we need to rebuild the texture
  14567. // in case of a webgl context lost
  14568. texture._buffer = img;
  14569. }
  14570. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14571. var gl = _this._gl;
  14572. var isPot = (img.width === potWidth && img.height === potHeight);
  14573. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14574. if (isPot) {
  14575. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14576. return false;
  14577. }
  14578. // Using shaders to rescale because canvas.drawImage is lossy
  14579. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14580. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  14581. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14582. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14583. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14584. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14585. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14586. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  14587. _this._releaseTexture(source);
  14588. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14589. continuationCallback();
  14590. });
  14591. return true;
  14592. }, samplingMode);
  14593. };
  14594. if (!fromData || isBase64)
  14595. if (buffer instanceof HTMLImageElement) {
  14596. onload(buffer);
  14597. }
  14598. else {
  14599. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14600. }
  14601. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  14602. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  14603. else
  14604. onload(buffer);
  14605. }
  14606. return texture;
  14607. };
  14608. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14609. var _this = this;
  14610. var rtt = this.createRenderTargetTexture({
  14611. width: destination.width,
  14612. height: destination.height,
  14613. }, {
  14614. generateMipMaps: false,
  14615. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14616. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  14617. generateDepthBuffer: false,
  14618. generateStencilBuffer: false
  14619. });
  14620. if (!this._rescalePostProcess) {
  14621. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14622. }
  14623. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14624. _this._rescalePostProcess.onApply = function (effect) {
  14625. effect._bindTexture("textureSampler", source);
  14626. };
  14627. var hostingScene = scene;
  14628. if (!hostingScene) {
  14629. hostingScene = _this.scenes[_this.scenes.length - 1];
  14630. }
  14631. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14632. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14633. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14634. _this.unBindFramebuffer(rtt);
  14635. _this._releaseTexture(rtt);
  14636. if (onComplete) {
  14637. onComplete();
  14638. }
  14639. });
  14640. };
  14641. /**
  14642. * Update a raw texture
  14643. * @param texture defines the texture to update
  14644. * @param data defines the data to store in the texture
  14645. * @param format defines the format of the data
  14646. * @param invertY defines if data must be stored with Y axis inverted
  14647. * @param compression defines the compression used (null by default)
  14648. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14649. */
  14650. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14651. if (compression === void 0) { compression = null; }
  14652. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14653. if (!texture) {
  14654. return;
  14655. }
  14656. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14657. var internalFormat = this._getInternalFormat(format);
  14658. var textureType = this._getWebGLTextureType(type);
  14659. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14660. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14661. if (!this._doNotHandleContextLost) {
  14662. texture._bufferView = data;
  14663. texture.format = format;
  14664. texture.type = type;
  14665. texture.invertY = invertY;
  14666. texture._compression = compression;
  14667. }
  14668. if (texture.width % 4 !== 0) {
  14669. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14670. }
  14671. if (compression && data) {
  14672. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14673. }
  14674. else {
  14675. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14676. }
  14677. if (texture.generateMipMaps) {
  14678. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14679. }
  14680. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14681. // this.resetTextureCache();
  14682. texture.isReady = true;
  14683. };
  14684. /**
  14685. * Creates a raw texture
  14686. * @param data defines the data to store in the texture
  14687. * @param width defines the width of the texture
  14688. * @param height defines the height of the texture
  14689. * @param format defines the format of the data
  14690. * @param generateMipMaps defines if the engine should generate the mip levels
  14691. * @param invertY defines if data must be stored with Y axis inverted
  14692. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14693. * @param compression defines the compression used (null by default)
  14694. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14695. * @returns the raw texture inside an InternalTexture
  14696. */
  14697. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14698. if (compression === void 0) { compression = null; }
  14699. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14700. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14701. texture.baseWidth = width;
  14702. texture.baseHeight = height;
  14703. texture.width = width;
  14704. texture.height = height;
  14705. texture.format = format;
  14706. texture.generateMipMaps = generateMipMaps;
  14707. texture.samplingMode = samplingMode;
  14708. texture.invertY = invertY;
  14709. texture._compression = compression;
  14710. texture.type = type;
  14711. if (!this._doNotHandleContextLost) {
  14712. texture._bufferView = data;
  14713. }
  14714. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14715. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14716. // Filters
  14717. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14718. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14719. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14720. if (generateMipMaps) {
  14721. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14722. }
  14723. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14724. this._internalTexturesCache.push(texture);
  14725. return texture;
  14726. };
  14727. /**
  14728. * Creates a dynamic texture
  14729. * @param width defines the width of the texture
  14730. * @param height defines the height of the texture
  14731. * @param generateMipMaps defines if the engine should generate the mip levels
  14732. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14733. * @returns the dynamic texture inside an InternalTexture
  14734. */
  14735. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14736. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14737. texture.baseWidth = width;
  14738. texture.baseHeight = height;
  14739. if (generateMipMaps) {
  14740. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14741. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14742. }
  14743. // this.resetTextureCache();
  14744. texture.width = width;
  14745. texture.height = height;
  14746. texture.isReady = false;
  14747. texture.generateMipMaps = generateMipMaps;
  14748. texture.samplingMode = samplingMode;
  14749. this.updateTextureSamplingMode(samplingMode, texture);
  14750. this._internalTexturesCache.push(texture);
  14751. return texture;
  14752. };
  14753. /**
  14754. * Update the sampling mode of a given texture
  14755. * @param samplingMode defines the required sampling mode
  14756. * @param texture defines the texture to update
  14757. */
  14758. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14759. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  14760. if (texture.isCube) {
  14761. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14762. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14763. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14764. }
  14765. else if (texture.is3D) {
  14766. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14767. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14768. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14769. }
  14770. else {
  14771. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14772. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14773. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14774. }
  14775. texture.samplingMode = samplingMode;
  14776. };
  14777. /**
  14778. * Update the content of a dynamic texture
  14779. * @param texture defines the texture to update
  14780. * @param canvas defines the canvas containing the source
  14781. * @param invertY defines if data must be stored with Y axis inverted
  14782. * @param premulAlpha defines if alpha is stored as premultiplied
  14783. * @param format defines the format of the data
  14784. */
  14785. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14786. if (premulAlpha === void 0) { premulAlpha = false; }
  14787. if (!texture) {
  14788. return;
  14789. }
  14790. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14791. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  14792. if (premulAlpha) {
  14793. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14794. }
  14795. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14796. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14797. if (texture.generateMipMaps) {
  14798. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14799. }
  14800. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14801. if (premulAlpha) {
  14802. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14803. }
  14804. texture.isReady = true;
  14805. };
  14806. /**
  14807. * Update a video texture
  14808. * @param texture defines the texture to update
  14809. * @param video defines the video element to use
  14810. * @param invertY defines if data must be stored with Y axis inverted
  14811. */
  14812. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  14813. if (!texture || texture._isDisabled) {
  14814. return;
  14815. }
  14816. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14817. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  14818. try {
  14819. // Testing video texture support
  14820. if (this._videoTextureSupported === undefined) {
  14821. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14822. if (this._gl.getError() !== 0) {
  14823. this._videoTextureSupported = false;
  14824. }
  14825. else {
  14826. this._videoTextureSupported = true;
  14827. }
  14828. }
  14829. // Copy video through the current working canvas if video texture is not supported
  14830. if (!this._videoTextureSupported) {
  14831. if (!texture._workingCanvas) {
  14832. texture._workingCanvas = document.createElement("canvas");
  14833. var context = texture._workingCanvas.getContext("2d");
  14834. if (!context) {
  14835. throw new Error("Unable to get 2d context");
  14836. }
  14837. texture._workingContext = context;
  14838. texture._workingCanvas.width = texture.width;
  14839. texture._workingCanvas.height = texture.height;
  14840. }
  14841. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  14842. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  14843. }
  14844. else {
  14845. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14846. }
  14847. if (texture.generateMipMaps) {
  14848. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14849. }
  14850. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14851. // this.resetTextureCache();
  14852. texture.isReady = true;
  14853. }
  14854. catch (ex) {
  14855. // Something unexpected
  14856. // Let's disable the texture
  14857. texture._isDisabled = true;
  14858. }
  14859. };
  14860. /**
  14861. * Updates a depth texture Comparison Mode and Function.
  14862. * If the comparison Function is equal to 0, the mode will be set to none.
  14863. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  14864. * @param texture The texture to set the comparison function for
  14865. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  14866. */
  14867. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  14868. if (this.webGLVersion === 1) {
  14869. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  14870. return;
  14871. }
  14872. var gl = this._gl;
  14873. if (texture.isCube) {
  14874. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14875. if (comparisonFunction === 0) {
  14876. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14877. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14878. }
  14879. else {
  14880. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14881. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14882. }
  14883. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14884. }
  14885. else {
  14886. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14887. if (comparisonFunction === 0) {
  14888. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14889. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14890. }
  14891. else {
  14892. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14893. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14894. }
  14895. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14896. }
  14897. texture._comparisonFunction = comparisonFunction;
  14898. };
  14899. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  14900. var width = size.width || size;
  14901. var height = size.height || size;
  14902. internalTexture.baseWidth = width;
  14903. internalTexture.baseHeight = height;
  14904. internalTexture.width = width;
  14905. internalTexture.height = height;
  14906. internalTexture.isReady = true;
  14907. internalTexture.samples = 1;
  14908. internalTexture.generateMipMaps = false;
  14909. internalTexture._generateDepthBuffer = true;
  14910. internalTexture._generateStencilBuffer = generateStencil;
  14911. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  14912. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  14913. internalTexture._comparisonFunction = comparisonFunction;
  14914. var gl = this._gl;
  14915. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  14916. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  14917. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  14918. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  14919. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14920. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14921. if (comparisonFunction === 0) {
  14922. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14923. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14924. }
  14925. else {
  14926. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14927. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14928. }
  14929. };
  14930. /**
  14931. * Creates a depth stencil texture.
  14932. * This is only available in WebGL 2 or with the depth texture extension available.
  14933. * @param size The size of face edge in the texture.
  14934. * @param options The options defining the texture.
  14935. * @returns The texture
  14936. */
  14937. Engine.prototype.createDepthStencilTexture = function (size, options) {
  14938. if (options.isCube) {
  14939. var width = size.width || size;
  14940. return this._createDepthStencilCubeTexture(width, options);
  14941. }
  14942. else {
  14943. return this._createDepthStencilTexture(size, options);
  14944. }
  14945. };
  14946. /**
  14947. * Creates a depth stencil texture.
  14948. * This is only available in WebGL 2 or with the depth texture extension available.
  14949. * @param size The size of face edge in the texture.
  14950. * @param options The options defining the texture.
  14951. * @returns The texture
  14952. */
  14953. Engine.prototype._createDepthStencilTexture = function (size, options) {
  14954. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  14955. if (!this._caps.depthTextureExtension) {
  14956. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  14957. return internalTexture;
  14958. }
  14959. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  14960. var gl = this._gl;
  14961. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  14962. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  14963. if (this.webGLVersion > 1) {
  14964. if (internalOptions.generateStencil) {
  14965. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14966. }
  14967. else {
  14968. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14969. }
  14970. }
  14971. else {
  14972. if (internalOptions.generateStencil) {
  14973. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  14974. }
  14975. else {
  14976. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  14977. }
  14978. }
  14979. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  14980. return internalTexture;
  14981. };
  14982. /**
  14983. * Creates a depth stencil cube texture.
  14984. * This is only available in WebGL 2.
  14985. * @param size The size of face edge in the cube texture.
  14986. * @param options The options defining the cube texture.
  14987. * @returns The cube texture
  14988. */
  14989. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  14990. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  14991. internalTexture.isCube = true;
  14992. if (this.webGLVersion === 1) {
  14993. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  14994. return internalTexture;
  14995. }
  14996. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  14997. var gl = this._gl;
  14998. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  14999. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15000. // Create the depth/stencil buffer
  15001. for (var face = 0; face < 6; face++) {
  15002. if (internalOptions.generateStencil) {
  15003. 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);
  15004. }
  15005. else {
  15006. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15007. }
  15008. }
  15009. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15010. return internalTexture;
  15011. };
  15012. /**
  15013. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15014. * @param renderTarget The render target to set the frame buffer for
  15015. */
  15016. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15017. // Create the framebuffer
  15018. var internalTexture = renderTarget.getInternalTexture();
  15019. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15020. return;
  15021. }
  15022. var gl = this._gl;
  15023. var depthStencilTexture = renderTarget.depthStencilTexture;
  15024. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15025. if (depthStencilTexture.isCube) {
  15026. if (depthStencilTexture._generateStencilBuffer) {
  15027. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15028. }
  15029. else {
  15030. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15031. }
  15032. }
  15033. else {
  15034. if (depthStencilTexture._generateStencilBuffer) {
  15035. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15036. }
  15037. else {
  15038. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15039. }
  15040. }
  15041. this.bindUnboundFramebuffer(null);
  15042. };
  15043. /**
  15044. * Creates a new render target texture
  15045. * @param size defines the size of the texture
  15046. * @param options defines the options used to create the texture
  15047. * @returns a new render target texture stored in an InternalTexture
  15048. */
  15049. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15050. var fullOptions = new RenderTargetCreationOptions();
  15051. if (options !== undefined && typeof options === "object") {
  15052. fullOptions.generateMipMaps = options.generateMipMaps;
  15053. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15054. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15055. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15056. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15057. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15058. }
  15059. else {
  15060. fullOptions.generateMipMaps = options;
  15061. fullOptions.generateDepthBuffer = true;
  15062. fullOptions.generateStencilBuffer = false;
  15063. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15064. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15065. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15066. }
  15067. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15068. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15069. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15070. }
  15071. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15072. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15073. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15074. }
  15075. var gl = this._gl;
  15076. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15077. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15078. var width = size.width || size;
  15079. var height = size.height || size;
  15080. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  15081. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15082. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15083. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15084. }
  15085. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15086. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15087. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15088. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15089. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15090. // Create the framebuffer
  15091. var framebuffer = gl.createFramebuffer();
  15092. this.bindUnboundFramebuffer(framebuffer);
  15093. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15094. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15095. if (fullOptions.generateMipMaps) {
  15096. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15097. }
  15098. // Unbind
  15099. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15100. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15101. this.bindUnboundFramebuffer(null);
  15102. texture._framebuffer = framebuffer;
  15103. texture.baseWidth = width;
  15104. texture.baseHeight = height;
  15105. texture.width = width;
  15106. texture.height = height;
  15107. texture.isReady = true;
  15108. texture.samples = 1;
  15109. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15110. texture.samplingMode = fullOptions.samplingMode;
  15111. texture.type = fullOptions.type;
  15112. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15113. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15114. // this.resetTextureCache();
  15115. this._internalTexturesCache.push(texture);
  15116. return texture;
  15117. };
  15118. /**
  15119. * Create a multi render target texture
  15120. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15121. * @param size defines the size of the texture
  15122. * @param options defines the creation options
  15123. * @returns the cube texture as an InternalTexture
  15124. */
  15125. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15126. var generateMipMaps = false;
  15127. var generateDepthBuffer = true;
  15128. var generateStencilBuffer = false;
  15129. var generateDepthTexture = false;
  15130. var textureCount = 1;
  15131. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15132. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15133. var types = new Array();
  15134. var samplingModes = new Array();
  15135. if (options !== undefined) {
  15136. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15137. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15138. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15139. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15140. textureCount = options.textureCount || 1;
  15141. if (options.types) {
  15142. types = options.types;
  15143. }
  15144. if (options.samplingModes) {
  15145. samplingModes = options.samplingModes;
  15146. }
  15147. }
  15148. var gl = this._gl;
  15149. // Create the framebuffer
  15150. var framebuffer = gl.createFramebuffer();
  15151. this.bindUnboundFramebuffer(framebuffer);
  15152. var width = size.width || size;
  15153. var height = size.height || size;
  15154. var textures = [];
  15155. var attachments = [];
  15156. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15157. for (var i = 0; i < textureCount; i++) {
  15158. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15159. var type = types[i] || defaultType;
  15160. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15161. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15162. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15163. }
  15164. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15165. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15166. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15167. }
  15168. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15169. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15170. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15171. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15172. }
  15173. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15174. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15175. textures.push(texture);
  15176. attachments.push(attachment);
  15177. gl.activeTexture(gl["TEXTURE" + i]);
  15178. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15179. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15180. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15181. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15182. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15183. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15184. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15185. if (generateMipMaps) {
  15186. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15187. }
  15188. // Unbind
  15189. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15190. texture._framebuffer = framebuffer;
  15191. texture._depthStencilBuffer = depthStencilBuffer;
  15192. texture.baseWidth = width;
  15193. texture.baseHeight = height;
  15194. texture.width = width;
  15195. texture.height = height;
  15196. texture.isReady = true;
  15197. texture.samples = 1;
  15198. texture.generateMipMaps = generateMipMaps;
  15199. texture.samplingMode = samplingMode;
  15200. texture.type = type;
  15201. texture._generateDepthBuffer = generateDepthBuffer;
  15202. texture._generateStencilBuffer = generateStencilBuffer;
  15203. texture._attachments = attachments;
  15204. this._internalTexturesCache.push(texture);
  15205. }
  15206. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15207. // Depth texture
  15208. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15209. gl.activeTexture(gl.TEXTURE0);
  15210. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15211. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15212. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15213. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15214. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15215. 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);
  15216. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15217. depthTexture._framebuffer = framebuffer;
  15218. depthTexture.baseWidth = width;
  15219. depthTexture.baseHeight = height;
  15220. depthTexture.width = width;
  15221. depthTexture.height = height;
  15222. depthTexture.isReady = true;
  15223. depthTexture.samples = 1;
  15224. depthTexture.generateMipMaps = generateMipMaps;
  15225. depthTexture.samplingMode = gl.NEAREST;
  15226. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15227. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15228. textures.push(depthTexture);
  15229. this._internalTexturesCache.push(depthTexture);
  15230. }
  15231. gl.drawBuffers(attachments);
  15232. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15233. this.bindUnboundFramebuffer(null);
  15234. this.resetTextureCache();
  15235. return textures;
  15236. };
  15237. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15238. if (samples === void 0) { samples = 1; }
  15239. var depthStencilBuffer = null;
  15240. var gl = this._gl;
  15241. // Create the depth/stencil buffer
  15242. if (generateStencilBuffer) {
  15243. depthStencilBuffer = gl.createRenderbuffer();
  15244. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15245. if (samples > 1) {
  15246. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15247. }
  15248. else {
  15249. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15250. }
  15251. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15252. }
  15253. else if (generateDepthBuffer) {
  15254. depthStencilBuffer = gl.createRenderbuffer();
  15255. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15256. if (samples > 1) {
  15257. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15258. }
  15259. else {
  15260. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15261. }
  15262. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15263. }
  15264. return depthStencilBuffer;
  15265. };
  15266. /**
  15267. * Updates the sample count of a render target texture
  15268. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15269. * @param texture defines the texture to update
  15270. * @param samples defines the sample count to set
  15271. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15272. */
  15273. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15274. if (this.webGLVersion < 2 || !texture) {
  15275. return 1;
  15276. }
  15277. if (texture.samples === samples) {
  15278. return samples;
  15279. }
  15280. var gl = this._gl;
  15281. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15282. // Dispose previous render buffers
  15283. if (texture._depthStencilBuffer) {
  15284. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15285. texture._depthStencilBuffer = null;
  15286. }
  15287. if (texture._MSAAFramebuffer) {
  15288. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15289. texture._MSAAFramebuffer = null;
  15290. }
  15291. if (texture._MSAARenderBuffer) {
  15292. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15293. texture._MSAARenderBuffer = null;
  15294. }
  15295. if (samples > 1) {
  15296. var framebuffer = gl.createFramebuffer();
  15297. if (!framebuffer) {
  15298. throw new Error("Unable to create multi sampled framebuffer");
  15299. }
  15300. texture._MSAAFramebuffer = framebuffer;
  15301. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15302. var colorRenderbuffer = gl.createRenderbuffer();
  15303. if (!colorRenderbuffer) {
  15304. throw new Error("Unable to create multi sampled framebuffer");
  15305. }
  15306. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15307. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15308. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15309. texture._MSAARenderBuffer = colorRenderbuffer;
  15310. }
  15311. else {
  15312. this.bindUnboundFramebuffer(texture._framebuffer);
  15313. }
  15314. texture.samples = samples;
  15315. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15316. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15317. this.bindUnboundFramebuffer(null);
  15318. return samples;
  15319. };
  15320. /**
  15321. * Update the sample count for a given multiple render target texture
  15322. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15323. * @param textures defines the textures to update
  15324. * @param samples defines the sample count to set
  15325. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15326. */
  15327. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15328. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15329. return 1;
  15330. }
  15331. if (textures[0].samples === samples) {
  15332. return samples;
  15333. }
  15334. var gl = this._gl;
  15335. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15336. // Dispose previous render buffers
  15337. if (textures[0]._depthStencilBuffer) {
  15338. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15339. textures[0]._depthStencilBuffer = null;
  15340. }
  15341. if (textures[0]._MSAAFramebuffer) {
  15342. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15343. textures[0]._MSAAFramebuffer = null;
  15344. }
  15345. for (var i = 0; i < textures.length; i++) {
  15346. if (textures[i]._MSAARenderBuffer) {
  15347. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15348. textures[i]._MSAARenderBuffer = null;
  15349. }
  15350. }
  15351. if (samples > 1) {
  15352. var framebuffer = gl.createFramebuffer();
  15353. if (!framebuffer) {
  15354. throw new Error("Unable to create multi sampled framebuffer");
  15355. }
  15356. this.bindUnboundFramebuffer(framebuffer);
  15357. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15358. var attachments = [];
  15359. for (var i = 0; i < textures.length; i++) {
  15360. var texture = textures[i];
  15361. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15362. var colorRenderbuffer = gl.createRenderbuffer();
  15363. if (!colorRenderbuffer) {
  15364. throw new Error("Unable to create multi sampled framebuffer");
  15365. }
  15366. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15367. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15368. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15369. texture._MSAAFramebuffer = framebuffer;
  15370. texture._MSAARenderBuffer = colorRenderbuffer;
  15371. texture.samples = samples;
  15372. texture._depthStencilBuffer = depthStencilBuffer;
  15373. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15374. attachments.push(attachment);
  15375. }
  15376. gl.drawBuffers(attachments);
  15377. }
  15378. else {
  15379. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15380. }
  15381. this.bindUnboundFramebuffer(null);
  15382. return samples;
  15383. };
  15384. /** @hidden */
  15385. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  15386. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  15387. };
  15388. /** @hidden */
  15389. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  15390. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15391. };
  15392. /**
  15393. * Creates a new render target cube texture
  15394. * @param size defines the size of the texture
  15395. * @param options defines the options used to create the texture
  15396. * @returns a new render target cube texture stored in an InternalTexture
  15397. */
  15398. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15399. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15400. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15401. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15402. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15403. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15404. }
  15405. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15406. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15407. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15408. }
  15409. var gl = this._gl;
  15410. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15411. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15412. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  15413. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15414. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15415. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15416. }
  15417. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15418. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15419. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15420. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15421. for (var face = 0; face < 6; face++) {
  15422. 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);
  15423. }
  15424. // Create the framebuffer
  15425. var framebuffer = gl.createFramebuffer();
  15426. this.bindUnboundFramebuffer(framebuffer);
  15427. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15428. // MipMaps
  15429. if (fullOptions.generateMipMaps) {
  15430. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15431. }
  15432. // Unbind
  15433. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15434. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15435. this.bindUnboundFramebuffer(null);
  15436. texture._framebuffer = framebuffer;
  15437. texture.width = size;
  15438. texture.height = size;
  15439. texture.isReady = true;
  15440. texture.isCube = true;
  15441. texture.samples = 1;
  15442. texture.generateMipMaps = fullOptions.generateMipMaps;
  15443. texture.samplingMode = fullOptions.samplingMode;
  15444. texture.type = fullOptions.type;
  15445. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15446. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15447. this._internalTexturesCache.push(texture);
  15448. return texture;
  15449. };
  15450. /**
  15451. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15452. * @param rootUrl defines the url where the file to load is located
  15453. * @param scene defines the current scene
  15454. * @param scale defines scale to apply to the mip map selection
  15455. * @param offset defines offset to apply to the mip map selection
  15456. * @param onLoad defines an optional callback raised when the texture is loaded
  15457. * @param onError defines an optional callback raised if there is an issue to load the texture
  15458. * @param format defines the format of the data
  15459. * @param forcedExtension defines the extension to use to pick the right loader
  15460. * @returns the cube texture as an InternalTexture
  15461. */
  15462. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  15463. var _this = this;
  15464. if (onLoad === void 0) { onLoad = null; }
  15465. if (onError === void 0) { onError = null; }
  15466. if (forcedExtension === void 0) { forcedExtension = null; }
  15467. var callback = function (loadData) {
  15468. if (!loadData) {
  15469. if (onLoad) {
  15470. onLoad(null);
  15471. }
  15472. return;
  15473. }
  15474. var texture = loadData.texture;
  15475. if (loadData.info.sphericalPolynomial) {
  15476. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15477. }
  15478. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15479. texture._lodGenerationScale = scale;
  15480. texture._lodGenerationOffset = offset;
  15481. if (_this._caps.textureLOD) {
  15482. // Do not add extra process if texture lod is supported.
  15483. if (onLoad) {
  15484. onLoad(texture);
  15485. }
  15486. return;
  15487. }
  15488. var mipSlices = 3;
  15489. var gl = _this._gl;
  15490. var width = loadData.width;
  15491. if (!width) {
  15492. return;
  15493. }
  15494. var textures = [];
  15495. for (var i = 0; i < mipSlices; i++) {
  15496. //compute LOD from even spacing in smoothness (matching shader calculation)
  15497. var smoothness = i / (mipSlices - 1);
  15498. var roughness = 1 - smoothness;
  15499. var minLODIndex = offset; // roughness = 0
  15500. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  15501. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15502. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15503. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15504. glTextureFromLod.isCube = true;
  15505. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15506. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15507. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15508. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15509. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15510. if (loadData.isDDS) {
  15511. var info = loadData.info;
  15512. var data = loadData.data;
  15513. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15514. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  15515. }
  15516. else {
  15517. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15518. }
  15519. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15520. // Wrap in a base texture for easy binding.
  15521. var lodTexture = new BABYLON.BaseTexture(scene);
  15522. lodTexture.isCube = true;
  15523. lodTexture._texture = glTextureFromLod;
  15524. glTextureFromLod.isReady = true;
  15525. textures.push(lodTexture);
  15526. }
  15527. texture._lodTextureHigh = textures[2];
  15528. texture._lodTextureMid = textures[1];
  15529. texture._lodTextureLow = textures[0];
  15530. if (onLoad) {
  15531. onLoad(texture);
  15532. }
  15533. };
  15534. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, true);
  15535. };
  15536. /**
  15537. * Creates a cube texture
  15538. * @param rootUrl defines the url where the files to load is located
  15539. * @param scene defines the current scene
  15540. * @param files defines the list of files to load (1 per face)
  15541. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15542. * @param onLoad defines an optional callback raised when the texture is loaded
  15543. * @param onError defines an optional callback raised if there is an issue to load the texture
  15544. * @param format defines the format of the data
  15545. * @param forcedExtension defines the extension to use to pick the right loader
  15546. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15547. * @returns the cube texture as an InternalTexture
  15548. */
  15549. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials) {
  15550. var _this = this;
  15551. if (onLoad === void 0) { onLoad = null; }
  15552. if (onError === void 0) { onError = null; }
  15553. if (forcedExtension === void 0) { forcedExtension = null; }
  15554. if (createPolynomials === void 0) { createPolynomials = false; }
  15555. var gl = this._gl;
  15556. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15557. texture.isCube = true;
  15558. texture.url = rootUrl;
  15559. texture.generateMipMaps = !noMipmap;
  15560. if (!this._doNotHandleContextLost) {
  15561. texture._extension = forcedExtension;
  15562. texture._files = files;
  15563. }
  15564. var isKTX = false;
  15565. var isDDS = false;
  15566. var lastDot = rootUrl.lastIndexOf('.');
  15567. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15568. if (this._textureFormatInUse) {
  15569. extension = this._textureFormatInUse;
  15570. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  15571. isKTX = true;
  15572. }
  15573. else {
  15574. isDDS = (extension === ".dds");
  15575. }
  15576. var onerror = function (request, exception) {
  15577. if (onError && request) {
  15578. onError(request.status + " " + request.statusText, exception);
  15579. }
  15580. };
  15581. if (isKTX) {
  15582. this._loadFile(rootUrl, function (data) {
  15583. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  15584. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  15585. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15586. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  15587. ktx.uploadLevels(_this._gl, !noMipmap);
  15588. _this.setCubeMapTextureParams(gl, loadMipmap);
  15589. texture.width = ktx.pixelWidth;
  15590. texture.height = ktx.pixelHeight;
  15591. texture.isReady = true;
  15592. }, undefined, undefined, true, onerror);
  15593. }
  15594. else if (isDDS) {
  15595. if (files && files.length === 6) {
  15596. this._cascadeLoadFiles(scene, function (imgs) {
  15597. var info;
  15598. var loadMipmap = false;
  15599. var width = 0;
  15600. for (var index = 0; index < imgs.length; index++) {
  15601. var data = imgs[index];
  15602. info = BABYLON.DDSTools.GetDDSInfo(data);
  15603. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15604. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15605. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15606. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  15607. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15608. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15609. }
  15610. texture.width = info.width;
  15611. texture.height = info.height;
  15612. texture.type = info.textureType;
  15613. width = info.width;
  15614. }
  15615. _this.setCubeMapTextureParams(gl, loadMipmap);
  15616. texture.isReady = true;
  15617. if (onLoad) {
  15618. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  15619. }
  15620. }, files, onError);
  15621. }
  15622. else {
  15623. this._loadFile(rootUrl, function (data) {
  15624. var info = BABYLON.DDSTools.GetDDSInfo(data);
  15625. if (createPolynomials) {
  15626. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15627. }
  15628. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15629. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15630. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15631. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  15632. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15633. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15634. }
  15635. _this.setCubeMapTextureParams(gl, loadMipmap);
  15636. texture.width = info.width;
  15637. texture.height = info.height;
  15638. texture.isReady = true;
  15639. texture.type = info.textureType;
  15640. if (onLoad) {
  15641. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  15642. }
  15643. }, undefined, undefined, true, onerror);
  15644. }
  15645. }
  15646. else {
  15647. if (!files) {
  15648. throw new Error("Cannot load cubemap because files were not defined");
  15649. }
  15650. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15651. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15652. var height = width;
  15653. _this._prepareWorkingCanvas();
  15654. if (!_this._workingCanvas || !_this._workingContext) {
  15655. return;
  15656. }
  15657. _this._workingCanvas.width = width;
  15658. _this._workingCanvas.height = height;
  15659. var faces = [
  15660. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15661. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15662. ];
  15663. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15664. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15665. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15666. for (var index = 0; index < faces.length; index++) {
  15667. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15668. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15669. }
  15670. if (!noMipmap) {
  15671. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15672. }
  15673. _this.setCubeMapTextureParams(gl, !noMipmap);
  15674. texture.width = width;
  15675. texture.height = height;
  15676. texture.isReady = true;
  15677. if (format) {
  15678. texture.format = format;
  15679. }
  15680. texture.onLoadedObservable.notifyObservers(texture);
  15681. texture.onLoadedObservable.clear();
  15682. if (onLoad) {
  15683. onLoad();
  15684. }
  15685. }, files, onError);
  15686. }
  15687. this._internalTexturesCache.push(texture);
  15688. return texture;
  15689. };
  15690. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  15691. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15692. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15693. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15694. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15695. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15696. // this.resetTextureCache();
  15697. };
  15698. /**
  15699. * Update a raw cube texture
  15700. * @param texture defines the texture to udpdate
  15701. * @param data defines the data to store
  15702. * @param format defines the data format
  15703. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15704. * @param invertY defines if data must be stored with Y axis inverted
  15705. * @param compression defines the compression used (null by default)
  15706. * @param level defines which level of the texture to update
  15707. */
  15708. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15709. if (compression === void 0) { compression = null; }
  15710. if (level === void 0) { level = 0; }
  15711. texture._bufferViewArray = data;
  15712. texture.format = format;
  15713. texture.type = type;
  15714. texture.invertY = invertY;
  15715. texture._compression = compression;
  15716. var gl = this._gl;
  15717. var textureType = this._getWebGLTextureType(type);
  15718. var internalFormat = this._getInternalFormat(format);
  15719. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15720. var needConversion = false;
  15721. if (internalFormat === gl.RGB) {
  15722. internalFormat = gl.RGBA;
  15723. needConversion = true;
  15724. }
  15725. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15726. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15727. if (texture.width % 4 !== 0) {
  15728. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15729. }
  15730. // Data are known to be in +X +Y +Z -X -Y -Z
  15731. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15732. var faceData = data[faceIndex];
  15733. if (compression) {
  15734. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15735. }
  15736. else {
  15737. if (needConversion) {
  15738. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15739. }
  15740. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15741. }
  15742. }
  15743. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15744. if (isPot && texture.generateMipMaps && level === 0) {
  15745. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15746. }
  15747. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15748. // this.resetTextureCache();
  15749. texture.isReady = true;
  15750. };
  15751. /**
  15752. * Creates a new raw cube texture
  15753. * @param data defines the array of data to use to create each face
  15754. * @param size defines the size of the textures
  15755. * @param format defines the format of the data
  15756. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15757. * @param generateMipMaps defines if the engine should generate the mip levels
  15758. * @param invertY defines if data must be stored with Y axis inverted
  15759. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15760. * @param compression defines the compression used (null by default)
  15761. * @returns the cube texture as an InternalTexture
  15762. */
  15763. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15764. if (compression === void 0) { compression = null; }
  15765. var gl = this._gl;
  15766. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15767. texture.isCube = true;
  15768. texture.generateMipMaps = generateMipMaps;
  15769. texture.format = format;
  15770. texture.type = type;
  15771. if (!this._doNotHandleContextLost) {
  15772. texture._bufferViewArray = data;
  15773. }
  15774. var textureType = this._getWebGLTextureType(type);
  15775. var internalFormat = this._getInternalFormat(format);
  15776. if (internalFormat === gl.RGB) {
  15777. internalFormat = gl.RGBA;
  15778. }
  15779. var width = size;
  15780. var height = width;
  15781. texture.width = width;
  15782. texture.height = height;
  15783. // Double check on POT to generate Mips.
  15784. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15785. if (!isPot) {
  15786. generateMipMaps = false;
  15787. }
  15788. // Upload data if needed. The texture won't be ready until then.
  15789. if (data) {
  15790. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  15791. }
  15792. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15793. // Filters
  15794. if (data && generateMipMaps) {
  15795. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15796. }
  15797. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  15798. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15799. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15800. }
  15801. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  15802. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15803. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15804. }
  15805. else {
  15806. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15807. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15808. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15809. }
  15810. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15811. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15812. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15813. return texture;
  15814. };
  15815. /**
  15816. * Creates a new raw cube texture from a specified url
  15817. * @param url defines the url where the data is located
  15818. * @param scene defines the current scene
  15819. * @param size defines the size of the textures
  15820. * @param format defines the format of the data
  15821. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15822. * @param noMipmap defines if the engine should avoid generating the mip levels
  15823. * @param callback defines a callback used to extract texture data from loaded data
  15824. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  15825. * @param onLoad defines a callback called when texture is loaded
  15826. * @param onError defines a callback called if there is an error
  15827. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15828. * @param invertY defines if data must be stored with Y axis inverted
  15829. * @returns the cube texture as an InternalTexture
  15830. */
  15831. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  15832. var _this = this;
  15833. if (onLoad === void 0) { onLoad = null; }
  15834. if (onError === void 0) { onError = null; }
  15835. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  15836. if (invertY === void 0) { invertY = false; }
  15837. var gl = this._gl;
  15838. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  15839. scene._addPendingData(texture);
  15840. texture.url = url;
  15841. this._internalTexturesCache.push(texture);
  15842. var onerror = function (request, exception) {
  15843. scene._removePendingData(texture);
  15844. if (onError && request) {
  15845. onError(request.status + " " + request.statusText, exception);
  15846. }
  15847. };
  15848. var internalCallback = function (data) {
  15849. var width = texture.width;
  15850. var faceDataArrays = callback(data);
  15851. if (!faceDataArrays) {
  15852. return;
  15853. }
  15854. if (mipmapGenerator) {
  15855. var textureType = _this._getWebGLTextureType(type);
  15856. var internalFormat = _this._getInternalFormat(format);
  15857. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  15858. var needConversion = false;
  15859. if (internalFormat === gl.RGB) {
  15860. internalFormat = gl.RGBA;
  15861. needConversion = true;
  15862. }
  15863. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15864. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15865. var mipData = mipmapGenerator(faceDataArrays);
  15866. for (var level = 0; level < mipData.length; level++) {
  15867. var mipSize = width >> level;
  15868. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15869. var mipFaceData = mipData[level][faceIndex];
  15870. if (needConversion) {
  15871. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  15872. }
  15873. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  15874. }
  15875. }
  15876. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15877. }
  15878. else {
  15879. texture.generateMipMaps = !noMipmap;
  15880. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  15881. }
  15882. texture.isReady = true;
  15883. // this.resetTextureCache();
  15884. scene._removePendingData(texture);
  15885. if (onLoad) {
  15886. onLoad();
  15887. }
  15888. };
  15889. this._loadFile(url, function (data) {
  15890. internalCallback(data);
  15891. }, undefined, scene.database, true, onerror);
  15892. return texture;
  15893. };
  15894. ;
  15895. /**
  15896. * Update a raw 3D texture
  15897. * @param texture defines the texture to update
  15898. * @param data defines the data to store
  15899. * @param format defines the data format
  15900. * @param invertY defines if data must be stored with Y axis inverted
  15901. * @param compression defines the used compression (can be null)
  15902. */
  15903. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  15904. if (compression === void 0) { compression = null; }
  15905. var internalFormat = this._getInternalFormat(format);
  15906. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15907. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15908. if (!this._doNotHandleContextLost) {
  15909. texture._bufferView = data;
  15910. texture.format = format;
  15911. texture.invertY = invertY;
  15912. texture._compression = compression;
  15913. }
  15914. if (texture.width % 4 !== 0) {
  15915. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  15916. }
  15917. if (compression && data) {
  15918. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  15919. }
  15920. else {
  15921. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  15922. }
  15923. if (texture.generateMipMaps) {
  15924. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  15925. }
  15926. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15927. // this.resetTextureCache();
  15928. texture.isReady = true;
  15929. };
  15930. /**
  15931. * Creates a new raw 3D texture
  15932. * @param data defines the data used to create the texture
  15933. * @param width defines the width of the texture
  15934. * @param height defines the height of the texture
  15935. * @param depth defines the depth of the texture
  15936. * @param format defines the format of the texture
  15937. * @param generateMipMaps defines if the engine must generate mip levels
  15938. * @param invertY defines if data must be stored with Y axis inverted
  15939. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15940. * @param compression defines the compressed used (can be null)
  15941. * @returns a new raw 3D texture (stored in an InternalTexture)
  15942. */
  15943. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  15944. if (compression === void 0) { compression = null; }
  15945. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  15946. texture.baseWidth = width;
  15947. texture.baseHeight = height;
  15948. texture.baseDepth = depth;
  15949. texture.width = width;
  15950. texture.height = height;
  15951. texture.depth = depth;
  15952. texture.format = format;
  15953. texture.generateMipMaps = generateMipMaps;
  15954. texture.samplingMode = samplingMode;
  15955. texture.is3D = true;
  15956. if (!this._doNotHandleContextLost) {
  15957. texture._bufferView = data;
  15958. }
  15959. this.updateRawTexture3D(texture, data, format, invertY, compression);
  15960. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  15961. // Filters
  15962. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  15963. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  15964. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15965. if (generateMipMaps) {
  15966. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  15967. }
  15968. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15969. this._internalTexturesCache.push(texture);
  15970. return texture;
  15971. };
  15972. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  15973. var gl = this._gl;
  15974. if (!gl) {
  15975. return;
  15976. }
  15977. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  15978. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15979. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15980. if (!noMipmap && !isCompressed) {
  15981. gl.generateMipmap(gl.TEXTURE_2D);
  15982. }
  15983. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15984. // this.resetTextureCache();
  15985. if (scene) {
  15986. scene._removePendingData(texture);
  15987. }
  15988. texture.onLoadedObservable.notifyObservers(texture);
  15989. texture.onLoadedObservable.clear();
  15990. };
  15991. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  15992. var _this = this;
  15993. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  15994. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  15995. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  15996. var gl = this._gl;
  15997. if (!gl) {
  15998. return;
  15999. }
  16000. if (!texture._webGLTexture) {
  16001. // this.resetTextureCache();
  16002. if (scene) {
  16003. scene._removePendingData(texture);
  16004. }
  16005. return;
  16006. }
  16007. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16008. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  16009. texture.baseWidth = width;
  16010. texture.baseHeight = height;
  16011. texture.width = potWidth;
  16012. texture.height = potHeight;
  16013. texture.isReady = true;
  16014. if (processFunction(potWidth, potHeight, function () {
  16015. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16016. })) {
  16017. // Returning as texture needs extra async steps
  16018. return;
  16019. }
  16020. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16021. };
  16022. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16023. // Create new RGBA data container.
  16024. var rgbaData;
  16025. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16026. rgbaData = new Float32Array(width * height * 4);
  16027. }
  16028. else {
  16029. rgbaData = new Uint32Array(width * height * 4);
  16030. }
  16031. // Convert each pixel.
  16032. for (var x = 0; x < width; x++) {
  16033. for (var y = 0; y < height; y++) {
  16034. var index = (y * width + x) * 3;
  16035. var newIndex = (y * width + x) * 4;
  16036. // Map Old Value to new value.
  16037. rgbaData[newIndex + 0] = rgbData[index + 0];
  16038. rgbaData[newIndex + 1] = rgbData[index + 1];
  16039. rgbaData[newIndex + 2] = rgbData[index + 2];
  16040. // Add fully opaque alpha channel.
  16041. rgbaData[newIndex + 3] = 1;
  16042. }
  16043. }
  16044. return rgbaData;
  16045. };
  16046. /** @hidden */
  16047. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16048. var gl = this._gl;
  16049. if (texture._framebuffer) {
  16050. gl.deleteFramebuffer(texture._framebuffer);
  16051. texture._framebuffer = null;
  16052. }
  16053. if (texture._depthStencilBuffer) {
  16054. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16055. texture._depthStencilBuffer = null;
  16056. }
  16057. if (texture._MSAAFramebuffer) {
  16058. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16059. texture._MSAAFramebuffer = null;
  16060. }
  16061. if (texture._MSAARenderBuffer) {
  16062. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16063. texture._MSAARenderBuffer = null;
  16064. }
  16065. };
  16066. /** @hidden */
  16067. Engine.prototype._releaseTexture = function (texture) {
  16068. var gl = this._gl;
  16069. this._releaseFramebufferObjects(texture);
  16070. gl.deleteTexture(texture._webGLTexture);
  16071. // Unbind channels
  16072. this.unbindAllTextures();
  16073. var index = this._internalTexturesCache.indexOf(texture);
  16074. if (index !== -1) {
  16075. this._internalTexturesCache.splice(index, 1);
  16076. }
  16077. // Integrated fixed lod samplers.
  16078. if (texture._lodTextureHigh) {
  16079. texture._lodTextureHigh.dispose();
  16080. }
  16081. if (texture._lodTextureMid) {
  16082. texture._lodTextureMid.dispose();
  16083. }
  16084. if (texture._lodTextureLow) {
  16085. texture._lodTextureLow.dispose();
  16086. }
  16087. // Set output texture of post process to null if the texture has been released/disposed
  16088. this.scenes.forEach(function (scene) {
  16089. scene.postProcesses.forEach(function (postProcess) {
  16090. if (postProcess._outputTexture == texture) {
  16091. postProcess._outputTexture = null;
  16092. }
  16093. });
  16094. scene.cameras.forEach(function (camera) {
  16095. camera._postProcesses.forEach(function (postProcess) {
  16096. if (postProcess) {
  16097. if (postProcess._outputTexture == texture) {
  16098. postProcess._outputTexture = null;
  16099. }
  16100. }
  16101. });
  16102. });
  16103. });
  16104. };
  16105. Engine.prototype.setProgram = function (program) {
  16106. if (this._currentProgram !== program) {
  16107. this._gl.useProgram(program);
  16108. this._currentProgram = program;
  16109. }
  16110. };
  16111. /**
  16112. * Binds an effect to the webGL context
  16113. * @param effect defines the effect to bind
  16114. */
  16115. Engine.prototype.bindSamplers = function (effect) {
  16116. this.setProgram(effect.getProgram());
  16117. var samplers = effect.getSamplers();
  16118. for (var index = 0; index < samplers.length; index++) {
  16119. var uniform = effect.getUniform(samplers[index]);
  16120. if (uniform) {
  16121. this._boundUniforms[index] = uniform;
  16122. }
  16123. }
  16124. this._currentEffect = null;
  16125. };
  16126. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16127. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16128. return;
  16129. }
  16130. // Remove
  16131. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16132. // Bind last to it
  16133. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16134. // Bind to dummy
  16135. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16136. };
  16137. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16138. if (!internalTexture) {
  16139. return -1;
  16140. }
  16141. internalTexture._initialSlot = channel;
  16142. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16143. if (channel !== internalTexture._designatedSlot) {
  16144. this._textureCollisions.addCount(1, false);
  16145. }
  16146. }
  16147. else {
  16148. if (channel !== internalTexture._designatedSlot) {
  16149. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16150. return internalTexture._designatedSlot;
  16151. }
  16152. else {
  16153. // No slot for this texture, let's pick a new one (if we find a free slot)
  16154. if (this._nextFreeTextureSlots.length) {
  16155. return this._nextFreeTextureSlots[0];
  16156. }
  16157. // We need to recycle the oldest bound texture, sorry.
  16158. this._textureCollisions.addCount(1, false);
  16159. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16160. }
  16161. }
  16162. }
  16163. return channel;
  16164. };
  16165. Engine.prototype._linkTrackers = function (previous, next) {
  16166. previous.next = next;
  16167. next.previous = previous;
  16168. };
  16169. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16170. var currentSlot = internalTexture._designatedSlot;
  16171. if (currentSlot === -1) {
  16172. return -1;
  16173. }
  16174. internalTexture._designatedSlot = -1;
  16175. if (this.disableTextureBindingOptimization) {
  16176. return -1;
  16177. }
  16178. // Remove from bound list
  16179. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16180. // Free the slot
  16181. this._boundTexturesCache[currentSlot] = null;
  16182. this._nextFreeTextureSlots.push(currentSlot);
  16183. return currentSlot;
  16184. };
  16185. Engine.prototype._activateCurrentTexture = function () {
  16186. if (this._currentTextureChannel !== this._activeChannel) {
  16187. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16188. this._currentTextureChannel = this._activeChannel;
  16189. }
  16190. };
  16191. /** @hidden */
  16192. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16193. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16194. if (force === void 0) { force = false; }
  16195. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16196. this._activeChannel = texture._designatedSlot;
  16197. }
  16198. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16199. var isTextureForRendering = texture && texture._initialSlot > -1;
  16200. if (currentTextureBound !== texture || force) {
  16201. if (currentTextureBound) {
  16202. this._removeDesignatedSlot(currentTextureBound);
  16203. }
  16204. this._activateCurrentTexture();
  16205. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16206. this._boundTexturesCache[this._activeChannel] = texture;
  16207. if (texture) {
  16208. if (!this.disableTextureBindingOptimization) {
  16209. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16210. if (slotIndex > -1) {
  16211. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16212. }
  16213. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16214. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16215. }
  16216. texture._designatedSlot = this._activeChannel;
  16217. }
  16218. }
  16219. else if (forTextureDataUpdate) {
  16220. this._activateCurrentTexture();
  16221. }
  16222. if (isTextureForRendering && !forTextureDataUpdate) {
  16223. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16224. }
  16225. };
  16226. /** @hidden */
  16227. Engine.prototype._bindTexture = function (channel, texture) {
  16228. if (channel < 0) {
  16229. return;
  16230. }
  16231. if (texture) {
  16232. channel = this._getCorrectTextureChannel(channel, texture);
  16233. }
  16234. this._activeChannel = channel;
  16235. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16236. };
  16237. /**
  16238. * Sets a texture to the webGL context from a postprocess
  16239. * @param channel defines the channel to use
  16240. * @param postProcess defines the source postprocess
  16241. */
  16242. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16243. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16244. };
  16245. /**
  16246. * Binds the output of the passed in post process to the texture channel specified
  16247. * @param channel The channel the texture should be bound to
  16248. * @param postProcess The post process which's output should be bound
  16249. */
  16250. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16251. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16252. };
  16253. /**
  16254. * Unbind all textures from the webGL context
  16255. */
  16256. Engine.prototype.unbindAllTextures = function () {
  16257. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16258. this._activeChannel = channel;
  16259. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16260. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16261. if (this.webGLVersion > 1) {
  16262. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16263. }
  16264. }
  16265. };
  16266. /**
  16267. * Sets a texture to the according uniform.
  16268. * @param channel The texture channel
  16269. * @param uniform The uniform to set
  16270. * @param texture The texture to apply
  16271. */
  16272. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16273. if (channel < 0) {
  16274. return;
  16275. }
  16276. if (uniform) {
  16277. this._boundUniforms[channel] = uniform;
  16278. }
  16279. this._setTexture(channel, texture);
  16280. };
  16281. /**
  16282. * Sets a depth stencil texture from a render target to the according uniform.
  16283. * @param channel The texture channel
  16284. * @param uniform The uniform to set
  16285. * @param texture The render target texture containing the depth stencil texture to apply
  16286. */
  16287. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16288. if (channel < 0) {
  16289. return;
  16290. }
  16291. if (uniform) {
  16292. this._boundUniforms[channel] = uniform;
  16293. }
  16294. if (!texture || !texture.depthStencilTexture) {
  16295. this._setTexture(channel, null);
  16296. }
  16297. else {
  16298. this._setTexture(channel, texture, false, true);
  16299. }
  16300. };
  16301. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16302. var uniform = this._boundUniforms[sourceSlot];
  16303. if (uniform._currentState === destination) {
  16304. return;
  16305. }
  16306. this._gl.uniform1i(uniform, destination);
  16307. uniform._currentState = destination;
  16308. };
  16309. Engine.prototype._getTextureWrapMode = function (mode) {
  16310. switch (mode) {
  16311. case BABYLON.Texture.WRAP_ADDRESSMODE:
  16312. return this._gl.REPEAT;
  16313. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  16314. return this._gl.CLAMP_TO_EDGE;
  16315. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  16316. return this._gl.MIRRORED_REPEAT;
  16317. }
  16318. return this._gl.REPEAT;
  16319. };
  16320. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16321. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16322. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16323. // Not ready?
  16324. if (!texture) {
  16325. if (this._boundTexturesCache[channel] != null) {
  16326. this._activeChannel = channel;
  16327. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16328. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16329. if (this.webGLVersion > 1) {
  16330. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16331. }
  16332. }
  16333. return false;
  16334. }
  16335. // Video
  16336. if (texture.video) {
  16337. this._activeChannel = channel;
  16338. texture.update();
  16339. }
  16340. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16341. texture.delayLoad();
  16342. return false;
  16343. }
  16344. var internalTexture;
  16345. if (depthStencilTexture) {
  16346. internalTexture = texture.depthStencilTexture;
  16347. }
  16348. else if (texture.isReady()) {
  16349. internalTexture = texture.getInternalTexture();
  16350. }
  16351. else if (texture.isCube) {
  16352. internalTexture = this.emptyCubeTexture;
  16353. }
  16354. else if (texture.is3D) {
  16355. internalTexture = this.emptyTexture3D;
  16356. }
  16357. else {
  16358. internalTexture = this.emptyTexture;
  16359. }
  16360. if (!isPartOfTextureArray) {
  16361. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16362. }
  16363. var needToBind = true;
  16364. if (this._boundTexturesCache[channel] === internalTexture) {
  16365. this._moveBoundTextureOnTop(internalTexture);
  16366. if (!isPartOfTextureArray) {
  16367. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16368. }
  16369. needToBind = false;
  16370. }
  16371. this._activeChannel = channel;
  16372. if (internalTexture && internalTexture.is3D) {
  16373. if (needToBind) {
  16374. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16375. }
  16376. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16377. internalTexture._cachedWrapU = texture.wrapU;
  16378. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16379. }
  16380. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16381. internalTexture._cachedWrapV = texture.wrapV;
  16382. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16383. }
  16384. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16385. internalTexture._cachedWrapR = texture.wrapR;
  16386. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16387. }
  16388. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16389. }
  16390. else if (internalTexture && internalTexture.isCube) {
  16391. if (needToBind) {
  16392. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16393. }
  16394. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16395. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16396. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16397. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16398. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16399. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16400. }
  16401. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16402. }
  16403. else {
  16404. if (needToBind) {
  16405. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16406. }
  16407. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16408. internalTexture._cachedWrapU = texture.wrapU;
  16409. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16410. }
  16411. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16412. internalTexture._cachedWrapV = texture.wrapV;
  16413. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16414. }
  16415. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16416. }
  16417. return true;
  16418. };
  16419. /**
  16420. * Sets an array of texture to the webGL context
  16421. * @param channel defines the channel where the texture array must be set
  16422. * @param uniform defines the associated uniform location
  16423. * @param textures defines the array of textures to bind
  16424. */
  16425. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16426. if (channel < 0 || !uniform) {
  16427. return;
  16428. }
  16429. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16430. this._textureUnits = new Int32Array(textures.length);
  16431. }
  16432. for (var i = 0; i < textures.length; i++) {
  16433. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16434. }
  16435. this._gl.uniform1iv(uniform, this._textureUnits);
  16436. for (var index = 0; index < textures.length; index++) {
  16437. this._setTexture(this._textureUnits[index], textures[index], true);
  16438. }
  16439. };
  16440. /** @hidden */
  16441. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16442. var internalTexture = texture.getInternalTexture();
  16443. if (!internalTexture) {
  16444. return;
  16445. }
  16446. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16447. var value = texture.anisotropicFilteringLevel;
  16448. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  16449. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  16450. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  16451. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16452. }
  16453. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16454. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16455. internalTexture._cachedAnisotropicFilteringLevel = value;
  16456. }
  16457. };
  16458. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16459. this._bindTextureDirectly(target, texture, true, true);
  16460. this._gl.texParameterf(target, parameter, value);
  16461. };
  16462. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16463. if (texture) {
  16464. this._bindTextureDirectly(target, texture, true, true);
  16465. }
  16466. this._gl.texParameteri(target, parameter, value);
  16467. };
  16468. /**
  16469. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16470. * @param x defines the x coordinate of the rectangle where pixels must be read
  16471. * @param y defines the y coordinate of the rectangle where pixels must be read
  16472. * @param width defines the width of the rectangle where pixels must be read
  16473. * @param height defines the height of the rectangle where pixels must be read
  16474. * @returns a Uint8Array containing RGBA colors
  16475. */
  16476. Engine.prototype.readPixels = function (x, y, width, height) {
  16477. var data = new Uint8Array(height * width * 4);
  16478. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16479. return data;
  16480. };
  16481. /**
  16482. * Add an externaly attached data from its key.
  16483. * This method call will fail and return false, if such key already exists.
  16484. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16485. * @param key the unique key that identifies the data
  16486. * @param data the data object to associate to the key for this Engine instance
  16487. * @return true if no such key were already present and the data was added successfully, false otherwise
  16488. */
  16489. Engine.prototype.addExternalData = function (key, data) {
  16490. if (!this._externalData) {
  16491. this._externalData = new BABYLON.StringDictionary();
  16492. }
  16493. return this._externalData.add(key, data);
  16494. };
  16495. /**
  16496. * Get an externaly attached data from its key
  16497. * @param key the unique key that identifies the data
  16498. * @return the associated data, if present (can be null), or undefined if not present
  16499. */
  16500. Engine.prototype.getExternalData = function (key) {
  16501. if (!this._externalData) {
  16502. this._externalData = new BABYLON.StringDictionary();
  16503. }
  16504. return this._externalData.get(key);
  16505. };
  16506. /**
  16507. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16508. * @param key the unique key that identifies the data
  16509. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16510. * @return the associated data, can be null if the factory returned null.
  16511. */
  16512. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16513. if (!this._externalData) {
  16514. this._externalData = new BABYLON.StringDictionary();
  16515. }
  16516. return this._externalData.getOrAddWithFactory(key, factory);
  16517. };
  16518. /**
  16519. * Remove an externaly attached data from the Engine instance
  16520. * @param key the unique key that identifies the data
  16521. * @return true if the data was successfully removed, false if it doesn't exist
  16522. */
  16523. Engine.prototype.removeExternalData = function (key) {
  16524. if (!this._externalData) {
  16525. this._externalData = new BABYLON.StringDictionary();
  16526. }
  16527. return this._externalData.remove(key);
  16528. };
  16529. /**
  16530. * Unbind all vertex attributes from the webGL context
  16531. */
  16532. Engine.prototype.unbindAllAttributes = function () {
  16533. if (this._mustWipeVertexAttributes) {
  16534. this._mustWipeVertexAttributes = false;
  16535. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16536. this._gl.disableVertexAttribArray(i);
  16537. this._vertexAttribArraysEnabled[i] = false;
  16538. this._currentBufferPointers[i].active = false;
  16539. }
  16540. return;
  16541. }
  16542. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16543. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16544. continue;
  16545. }
  16546. this._gl.disableVertexAttribArray(i);
  16547. this._vertexAttribArraysEnabled[i] = false;
  16548. this._currentBufferPointers[i].active = false;
  16549. }
  16550. };
  16551. /**
  16552. * 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
  16553. */
  16554. Engine.prototype.releaseEffects = function () {
  16555. for (var name in this._compiledEffects) {
  16556. this._deleteProgram(this._compiledEffects[name]._program);
  16557. }
  16558. this._compiledEffects = {};
  16559. };
  16560. /**
  16561. * Dispose and release all associated resources
  16562. */
  16563. Engine.prototype.dispose = function () {
  16564. this.hideLoadingUI();
  16565. this.stopRenderLoop();
  16566. // Release postProcesses
  16567. while (this.postProcesses.length) {
  16568. this.postProcesses[0].dispose();
  16569. }
  16570. // Empty texture
  16571. if (this._emptyTexture) {
  16572. this._releaseTexture(this._emptyTexture);
  16573. this._emptyTexture = null;
  16574. }
  16575. if (this._emptyCubeTexture) {
  16576. this._releaseTexture(this._emptyCubeTexture);
  16577. this._emptyCubeTexture = null;
  16578. }
  16579. // Rescale PP
  16580. if (this._rescalePostProcess) {
  16581. this._rescalePostProcess.dispose();
  16582. }
  16583. // Release scenes
  16584. while (this.scenes.length) {
  16585. this.scenes[0].dispose();
  16586. }
  16587. // Release audio engine
  16588. if (Engine.audioEngine) {
  16589. Engine.audioEngine.dispose();
  16590. }
  16591. // Release effects
  16592. this.releaseEffects();
  16593. // Unbind
  16594. this.unbindAllAttributes();
  16595. this._boundUniforms = [];
  16596. if (this._dummyFramebuffer) {
  16597. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16598. }
  16599. //WebVR
  16600. this.disableVR();
  16601. // Events
  16602. if (BABYLON.Tools.IsWindowObjectExist()) {
  16603. window.removeEventListener("blur", this._onBlur);
  16604. window.removeEventListener("focus", this._onFocus);
  16605. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16606. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16607. if (this._renderingCanvas) {
  16608. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16609. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16610. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16611. if (!this._doNotHandleContextLost) {
  16612. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16613. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16614. }
  16615. }
  16616. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16617. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16618. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16619. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16620. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16621. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16622. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16623. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16624. if (this._onVrDisplayConnect) {
  16625. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16626. if (this._onVrDisplayDisconnect) {
  16627. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16628. }
  16629. if (this._onVrDisplayPresentChange) {
  16630. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16631. }
  16632. this._onVrDisplayConnect = null;
  16633. this._onVrDisplayDisconnect = null;
  16634. }
  16635. }
  16636. // Remove from Instances
  16637. var index = Engine.Instances.indexOf(this);
  16638. if (index >= 0) {
  16639. Engine.Instances.splice(index, 1);
  16640. }
  16641. this._workingCanvas = null;
  16642. this._workingContext = null;
  16643. this._currentBufferPointers = [];
  16644. this._renderingCanvas = null;
  16645. this._currentProgram = null;
  16646. this._bindedRenderFunction = null;
  16647. this.onResizeObservable.clear();
  16648. this.onCanvasBlurObservable.clear();
  16649. this.onCanvasFocusObservable.clear();
  16650. this.onCanvasPointerOutObservable.clear();
  16651. this.onBeginFrameObservable.clear();
  16652. this.onEndFrameObservable.clear();
  16653. BABYLON.Effect.ResetCache();
  16654. // Abort active requests
  16655. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16656. var request = _a[_i];
  16657. request.abort();
  16658. }
  16659. };
  16660. // Loading screen
  16661. /**
  16662. * Display the loading screen
  16663. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16664. */
  16665. Engine.prototype.displayLoadingUI = function () {
  16666. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16667. return;
  16668. }
  16669. var loadingScreen = this.loadingScreen;
  16670. if (loadingScreen) {
  16671. loadingScreen.displayLoadingUI();
  16672. }
  16673. };
  16674. /**
  16675. * Hide the loading screen
  16676. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16677. */
  16678. Engine.prototype.hideLoadingUI = function () {
  16679. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16680. return;
  16681. }
  16682. var loadingScreen = this.loadingScreen;
  16683. if (loadingScreen) {
  16684. loadingScreen.hideLoadingUI();
  16685. }
  16686. };
  16687. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16688. /**
  16689. * Gets the current loading screen object
  16690. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16691. */
  16692. get: function () {
  16693. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16694. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16695. return this._loadingScreen;
  16696. },
  16697. /**
  16698. * Sets the current loading screen object
  16699. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16700. */
  16701. set: function (loadingScreen) {
  16702. this._loadingScreen = loadingScreen;
  16703. },
  16704. enumerable: true,
  16705. configurable: true
  16706. });
  16707. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16708. /**
  16709. * Sets the current loading screen text
  16710. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16711. */
  16712. set: function (text) {
  16713. this.loadingScreen.loadingUIText = text;
  16714. },
  16715. enumerable: true,
  16716. configurable: true
  16717. });
  16718. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16719. /**
  16720. * Sets the current loading screen background color
  16721. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16722. */
  16723. set: function (color) {
  16724. this.loadingScreen.loadingUIBackgroundColor = color;
  16725. },
  16726. enumerable: true,
  16727. configurable: true
  16728. });
  16729. /**
  16730. * Attach a new callback raised when context lost event is fired
  16731. * @param callback defines the callback to call
  16732. */
  16733. Engine.prototype.attachContextLostEvent = function (callback) {
  16734. if (this._renderingCanvas) {
  16735. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16736. }
  16737. };
  16738. /**
  16739. * Attach a new callback raised when context restored event is fired
  16740. * @param callback defines the callback to call
  16741. */
  16742. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16743. if (this._renderingCanvas) {
  16744. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16745. }
  16746. };
  16747. /**
  16748. * Gets the source code of the vertex shader associated with a specific webGL program
  16749. * @param program defines the program to use
  16750. * @returns a string containing the source code of the vertex shader associated with the program
  16751. */
  16752. Engine.prototype.getVertexShaderSource = function (program) {
  16753. var shaders = this._gl.getAttachedShaders(program);
  16754. if (!shaders) {
  16755. return null;
  16756. }
  16757. return this._gl.getShaderSource(shaders[0]);
  16758. };
  16759. /**
  16760. * Gets the source code of the fragment shader associated with a specific webGL program
  16761. * @param program defines the program to use
  16762. * @returns a string containing the source code of the fragment shader associated with the program
  16763. */
  16764. Engine.prototype.getFragmentShaderSource = function (program) {
  16765. var shaders = this._gl.getAttachedShaders(program);
  16766. if (!shaders) {
  16767. return null;
  16768. }
  16769. return this._gl.getShaderSource(shaders[1]);
  16770. };
  16771. /**
  16772. * Get the current error code of the webGL context
  16773. * @returns the error code
  16774. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  16775. */
  16776. Engine.prototype.getError = function () {
  16777. return this._gl.getError();
  16778. };
  16779. // FPS
  16780. /**
  16781. * Gets the current framerate
  16782. * @returns a number representing the framerate
  16783. */
  16784. Engine.prototype.getFps = function () {
  16785. return this._fps;
  16786. };
  16787. /**
  16788. * Gets the time spent between current and previous frame
  16789. * @returns a number representing the delta time in ms
  16790. */
  16791. Engine.prototype.getDeltaTime = function () {
  16792. return this._deltaTime;
  16793. };
  16794. Engine.prototype._measureFps = function () {
  16795. this._performanceMonitor.sampleFrame();
  16796. this._fps = this._performanceMonitor.averageFPS;
  16797. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  16798. };
  16799. /** @hidden */
  16800. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  16801. if (faceIndex === void 0) { faceIndex = -1; }
  16802. var gl = this._gl;
  16803. if (!this._dummyFramebuffer) {
  16804. var dummy = gl.createFramebuffer();
  16805. if (!dummy) {
  16806. throw new Error("Unable to create dummy framebuffer");
  16807. }
  16808. this._dummyFramebuffer = dummy;
  16809. }
  16810. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  16811. if (faceIndex > -1) {
  16812. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  16813. }
  16814. else {
  16815. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  16816. }
  16817. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  16818. var buffer;
  16819. switch (readType) {
  16820. case gl.UNSIGNED_BYTE:
  16821. buffer = new Uint8Array(4 * width * height);
  16822. readType = gl.UNSIGNED_BYTE;
  16823. break;
  16824. default:
  16825. buffer = new Float32Array(4 * width * height);
  16826. readType = gl.FLOAT;
  16827. break;
  16828. }
  16829. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  16830. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  16831. return buffer;
  16832. };
  16833. Engine.prototype._canRenderToFloatFramebuffer = function () {
  16834. if (this._webGLVersion > 1) {
  16835. return this._caps.colorBufferFloat;
  16836. }
  16837. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  16838. };
  16839. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  16840. if (this._webGLVersion > 1) {
  16841. return this._caps.colorBufferFloat;
  16842. }
  16843. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  16844. };
  16845. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  16846. Engine.prototype._canRenderToFramebuffer = function (type) {
  16847. var gl = this._gl;
  16848. //clear existing errors
  16849. while (gl.getError() !== gl.NO_ERROR) { }
  16850. var successful = true;
  16851. var texture = gl.createTexture();
  16852. gl.bindTexture(gl.TEXTURE_2D, texture);
  16853. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  16854. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16855. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16856. var fb = gl.createFramebuffer();
  16857. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  16858. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  16859. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  16860. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  16861. successful = successful && (gl.getError() === gl.NO_ERROR);
  16862. //try render by clearing frame buffer's color buffer
  16863. if (successful) {
  16864. gl.clear(gl.COLOR_BUFFER_BIT);
  16865. successful = successful && (gl.getError() === gl.NO_ERROR);
  16866. }
  16867. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  16868. if (successful) {
  16869. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  16870. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16871. var readFormat = gl.RGBA;
  16872. var readType = gl.UNSIGNED_BYTE;
  16873. var buffer = new Uint8Array(4);
  16874. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  16875. successful = successful && (gl.getError() === gl.NO_ERROR);
  16876. }
  16877. //clean up
  16878. gl.deleteTexture(texture);
  16879. gl.deleteFramebuffer(fb);
  16880. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16881. //clear accumulated errors
  16882. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  16883. return successful;
  16884. };
  16885. /** @hidden */
  16886. Engine.prototype._getWebGLTextureType = function (type) {
  16887. if (type === Engine.TEXTURETYPE_FLOAT) {
  16888. return this._gl.FLOAT;
  16889. }
  16890. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16891. // Add Half Float Constant.
  16892. return this._gl.HALF_FLOAT_OES;
  16893. }
  16894. return this._gl.UNSIGNED_BYTE;
  16895. };
  16896. ;
  16897. Engine.prototype._getInternalFormat = function (format) {
  16898. var internalFormat = this._gl.RGBA;
  16899. switch (format) {
  16900. case Engine.TEXTUREFORMAT_ALPHA:
  16901. internalFormat = this._gl.ALPHA;
  16902. break;
  16903. case Engine.TEXTUREFORMAT_LUMINANCE:
  16904. internalFormat = this._gl.LUMINANCE;
  16905. break;
  16906. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  16907. internalFormat = this._gl.LUMINANCE_ALPHA;
  16908. break;
  16909. case Engine.TEXTUREFORMAT_RGB:
  16910. case Engine.TEXTUREFORMAT_RGB32F:
  16911. internalFormat = this._gl.RGB;
  16912. break;
  16913. case Engine.TEXTUREFORMAT_RGBA:
  16914. case Engine.TEXTUREFORMAT_RGBA32F:
  16915. internalFormat = this._gl.RGBA;
  16916. break;
  16917. case Engine.TEXTUREFORMAT_R32F:
  16918. internalFormat = this._gl.RED;
  16919. break;
  16920. case Engine.TEXTUREFORMAT_RG32F:
  16921. internalFormat = this._gl.RG;
  16922. break;
  16923. }
  16924. return internalFormat;
  16925. };
  16926. /** @hidden */
  16927. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  16928. if (this._webGLVersion === 1) {
  16929. if (format) {
  16930. switch (format) {
  16931. case Engine.TEXTUREFORMAT_LUMINANCE:
  16932. return this._gl.LUMINANCE;
  16933. }
  16934. }
  16935. return this._gl.RGBA;
  16936. }
  16937. if (type === Engine.TEXTURETYPE_FLOAT) {
  16938. if (format) {
  16939. switch (format) {
  16940. case Engine.TEXTUREFORMAT_R32F:
  16941. return this._gl.R32F;
  16942. case Engine.TEXTUREFORMAT_RG32F:
  16943. return this._gl.RG32F;
  16944. case Engine.TEXTUREFORMAT_RGB32F:
  16945. return this._gl.RGB32F;
  16946. }
  16947. }
  16948. return this._gl.RGBA32F;
  16949. }
  16950. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16951. return this._gl.RGBA16F;
  16952. }
  16953. if (format) {
  16954. switch (format) {
  16955. case Engine.TEXTUREFORMAT_LUMINANCE:
  16956. return this._gl.LUMINANCE;
  16957. case Engine.TEXTUREFORMAT_RGB:
  16958. return this._gl.RGB;
  16959. }
  16960. }
  16961. return this._gl.RGBA;
  16962. };
  16963. ;
  16964. /** @hidden */
  16965. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  16966. if (type === Engine.TEXTURETYPE_FLOAT) {
  16967. return this._gl.RGBA32F;
  16968. }
  16969. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  16970. return this._gl.RGBA16F;
  16971. }
  16972. return this._gl.RGBA8;
  16973. };
  16974. ;
  16975. /**
  16976. * Create a new webGL query (you must be sure that queries are supported by checking getCaps() function)
  16977. * @return the new query
  16978. */
  16979. Engine.prototype.createQuery = function () {
  16980. return this._gl.createQuery();
  16981. };
  16982. /**
  16983. * Delete and release a webGL query
  16984. * @param query defines the query to delete
  16985. * @return the current engine
  16986. */
  16987. Engine.prototype.deleteQuery = function (query) {
  16988. this._gl.deleteQuery(query);
  16989. return this;
  16990. };
  16991. /**
  16992. * Check if a given query has resolved and got its value
  16993. * @param query defines the query to check
  16994. * @returns true if the query got its value
  16995. */
  16996. Engine.prototype.isQueryResultAvailable = function (query) {
  16997. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  16998. };
  16999. /**
  17000. * Gets the value of a given query
  17001. * @param query defines the query to check
  17002. * @returns the value of the query
  17003. */
  17004. Engine.prototype.getQueryResult = function (query) {
  17005. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  17006. };
  17007. /**
  17008. * Initiates an occlusion query
  17009. * @param algorithmType defines the algorithm to use
  17010. * @param query defines the query to use
  17011. * @returns the current engine
  17012. * @see http://doc.babylonjs.com/features/occlusionquery
  17013. */
  17014. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  17015. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17016. this._gl.beginQuery(glAlgorithm, query);
  17017. return this;
  17018. };
  17019. /**
  17020. * Ends an occlusion query
  17021. * @see http://doc.babylonjs.com/features/occlusionquery
  17022. * @param algorithmType defines the algorithm to use
  17023. * @returns the current engine
  17024. */
  17025. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  17026. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17027. this._gl.endQuery(glAlgorithm);
  17028. return this;
  17029. };
  17030. /* Time queries */
  17031. Engine.prototype._createTimeQuery = function () {
  17032. var timerQuery = this._caps.timerQuery;
  17033. if (timerQuery.createQueryEXT) {
  17034. return timerQuery.createQueryEXT();
  17035. }
  17036. return this.createQuery();
  17037. };
  17038. Engine.prototype._deleteTimeQuery = function (query) {
  17039. var timerQuery = this._caps.timerQuery;
  17040. if (timerQuery.deleteQueryEXT) {
  17041. timerQuery.deleteQueryEXT(query);
  17042. return;
  17043. }
  17044. this.deleteQuery(query);
  17045. };
  17046. Engine.prototype._getTimeQueryResult = function (query) {
  17047. var timerQuery = this._caps.timerQuery;
  17048. if (timerQuery.getQueryObjectEXT) {
  17049. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  17050. }
  17051. return this.getQueryResult(query);
  17052. };
  17053. Engine.prototype._getTimeQueryAvailability = function (query) {
  17054. var timerQuery = this._caps.timerQuery;
  17055. if (timerQuery.getQueryObjectEXT) {
  17056. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  17057. }
  17058. return this.isQueryResultAvailable(query);
  17059. };
  17060. /**
  17061. * Starts a time query (used to measure time spent by the GPU on a specific frame)
  17062. * Please note that only one query can be issued at a time
  17063. * @returns a time token used to track the time span
  17064. */
  17065. Engine.prototype.startTimeQuery = function () {
  17066. var timerQuery = this._caps.timerQuery;
  17067. if (!timerQuery) {
  17068. return null;
  17069. }
  17070. var token = new BABYLON._TimeToken();
  17071. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17072. if (this._caps.canUseTimestampForTimerQuery) {
  17073. token._startTimeQuery = this._createTimeQuery();
  17074. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  17075. }
  17076. else {
  17077. if (this._currentNonTimestampToken) {
  17078. return this._currentNonTimestampToken;
  17079. }
  17080. token._timeElapsedQuery = this._createTimeQuery();
  17081. if (timerQuery.beginQueryEXT) {
  17082. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17083. }
  17084. else {
  17085. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17086. }
  17087. this._currentNonTimestampToken = token;
  17088. }
  17089. return token;
  17090. };
  17091. /**
  17092. * Ends a time query
  17093. * @param token defines the token used to measure the time span
  17094. * @returns the time spent (in ns)
  17095. */
  17096. Engine.prototype.endTimeQuery = function (token) {
  17097. var timerQuery = this._caps.timerQuery;
  17098. if (!timerQuery || !token) {
  17099. return -1;
  17100. }
  17101. if (this._caps.canUseTimestampForTimerQuery) {
  17102. if (!token._startTimeQuery) {
  17103. return -1;
  17104. }
  17105. if (!token._endTimeQuery) {
  17106. token._endTimeQuery = this._createTimeQuery();
  17107. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  17108. }
  17109. }
  17110. else if (!token._timeElapsedQueryEnded) {
  17111. if (!token._timeElapsedQuery) {
  17112. return -1;
  17113. }
  17114. if (timerQuery.endQueryEXT) {
  17115. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  17116. }
  17117. else {
  17118. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  17119. }
  17120. token._timeElapsedQueryEnded = true;
  17121. }
  17122. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17123. var available = false;
  17124. if (token._endTimeQuery) {
  17125. available = this._getTimeQueryAvailability(token._endTimeQuery);
  17126. }
  17127. else if (token._timeElapsedQuery) {
  17128. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  17129. }
  17130. if (available && !disjoint) {
  17131. var result = 0;
  17132. if (this._caps.canUseTimestampForTimerQuery) {
  17133. if (!token._startTimeQuery || !token._endTimeQuery) {
  17134. return -1;
  17135. }
  17136. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  17137. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  17138. result = timeEnd - timeStart;
  17139. this._deleteTimeQuery(token._startTimeQuery);
  17140. this._deleteTimeQuery(token._endTimeQuery);
  17141. token._startTimeQuery = null;
  17142. token._endTimeQuery = null;
  17143. }
  17144. else {
  17145. if (!token._timeElapsedQuery) {
  17146. return -1;
  17147. }
  17148. result = this._getTimeQueryResult(token._timeElapsedQuery);
  17149. this._deleteTimeQuery(token._timeElapsedQuery);
  17150. token._timeElapsedQuery = null;
  17151. token._timeElapsedQueryEnded = false;
  17152. this._currentNonTimestampToken = null;
  17153. }
  17154. return result;
  17155. }
  17156. return -1;
  17157. };
  17158. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  17159. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  17160. };
  17161. // Transform feedback
  17162. /**
  17163. * Creates a webGL transform feedback object
  17164. * Please makes sure to check webGLVersion property to check if you are running webGL 2+
  17165. * @returns the webGL transform feedback object
  17166. */
  17167. Engine.prototype.createTransformFeedback = function () {
  17168. return this._gl.createTransformFeedback();
  17169. };
  17170. /**
  17171. * Delete a webGL transform feedback object
  17172. * @param value defines the webGL transform feedback object to delete
  17173. */
  17174. Engine.prototype.deleteTransformFeedback = function (value) {
  17175. this._gl.deleteTransformFeedback(value);
  17176. };
  17177. /**
  17178. * Bind a webGL transform feedback object to the webgl context
  17179. * @param value defines the webGL transform feedback object to bind
  17180. */
  17181. Engine.prototype.bindTransformFeedback = function (value) {
  17182. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  17183. };
  17184. /**
  17185. * Begins a transform feedback operation
  17186. * @param usePoints defines if points or triangles must be used
  17187. */
  17188. Engine.prototype.beginTransformFeedback = function (usePoints) {
  17189. if (usePoints === void 0) { usePoints = true; }
  17190. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  17191. };
  17192. /**
  17193. * Ends a transform feedback operation
  17194. */
  17195. Engine.prototype.endTransformFeedback = function () {
  17196. this._gl.endTransformFeedback();
  17197. };
  17198. /**
  17199. * Specify the varyings to use with transform feedback
  17200. * @param program defines the associated webGL program
  17201. * @param value defines the list of strings representing the varying names
  17202. */
  17203. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  17204. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  17205. };
  17206. /**
  17207. * Bind a webGL buffer for a transform feedback operation
  17208. * @param value defines the webGL buffer to bind
  17209. */
  17210. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  17211. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  17212. };
  17213. /** @hidden */
  17214. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17215. var _this = this;
  17216. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17217. this._activeRequests.push(request);
  17218. request.onCompleteObservable.add(function (request) {
  17219. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17220. });
  17221. return request;
  17222. };
  17223. /** @hidden */
  17224. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17225. var _this = this;
  17226. return new Promise(function (resolve, reject) {
  17227. _this._loadFile(url, function (data) {
  17228. resolve(data);
  17229. }, undefined, database, useArrayBuffer, function (request, exception) {
  17230. reject(exception);
  17231. });
  17232. });
  17233. };
  17234. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17235. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17236. var onload = function (data) {
  17237. loadedFiles[index] = data;
  17238. loadedFiles._internalCount++;
  17239. if (loadedFiles._internalCount === 6) {
  17240. onfinish(loadedFiles);
  17241. }
  17242. };
  17243. var onerror = function (request, exception) {
  17244. if (onErrorCallBack && request) {
  17245. onErrorCallBack(request.status + " " + request.statusText, exception);
  17246. }
  17247. };
  17248. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17249. };
  17250. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17251. if (onError === void 0) { onError = null; }
  17252. var loadedFiles = [];
  17253. loadedFiles._internalCount = 0;
  17254. for (var index = 0; index < 6; index++) {
  17255. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17256. }
  17257. };
  17258. // Statics
  17259. /**
  17260. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17261. * @returns true if the engine can be created
  17262. * @ignorenaming
  17263. */
  17264. Engine.isSupported = function () {
  17265. try {
  17266. var tempcanvas = document.createElement("canvas");
  17267. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17268. return gl != null && !!window.WebGLRenderingContext;
  17269. }
  17270. catch (e) {
  17271. return false;
  17272. }
  17273. };
  17274. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17275. Engine.ExceptionList = [
  17276. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17277. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17278. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17279. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17280. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17281. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17282. ];
  17283. /** Gets the list of created engines */
  17284. Engine.Instances = new Array();
  17285. // Const statics
  17286. Engine._ALPHA_DISABLE = 0;
  17287. Engine._ALPHA_ADD = 1;
  17288. Engine._ALPHA_COMBINE = 2;
  17289. Engine._ALPHA_SUBTRACT = 3;
  17290. Engine._ALPHA_MULTIPLY = 4;
  17291. Engine._ALPHA_MAXIMIZED = 5;
  17292. Engine._ALPHA_ONEONE = 6;
  17293. Engine._ALPHA_PREMULTIPLIED = 7;
  17294. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17295. Engine._ALPHA_INTERPOLATE = 9;
  17296. Engine._ALPHA_SCREENMODE = 10;
  17297. Engine._DELAYLOADSTATE_NONE = 0;
  17298. Engine._DELAYLOADSTATE_LOADED = 1;
  17299. Engine._DELAYLOADSTATE_LOADING = 2;
  17300. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  17301. Engine._TEXTUREFORMAT_ALPHA = 0;
  17302. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  17303. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17304. Engine._TEXTUREFORMAT_RGB = 4;
  17305. Engine._TEXTUREFORMAT_RGBA = 5;
  17306. Engine._TEXTUREFORMAT_R32F = 6;
  17307. Engine._TEXTUREFORMAT_RG32F = 7;
  17308. Engine._TEXTUREFORMAT_RGB32F = 8;
  17309. Engine._TEXTUREFORMAT_RGBA32F = 9;
  17310. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  17311. Engine._TEXTURETYPE_FLOAT = 1;
  17312. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  17313. // Depht or Stencil test Constants.
  17314. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  17315. 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.
  17316. 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.
  17317. 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.
  17318. 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.
  17319. 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.
  17320. 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.
  17321. 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.
  17322. // Stencil Actions Constants.
  17323. Engine._KEEP = 0x1E00;
  17324. Engine._REPLACE = 0x1E01;
  17325. Engine._INCR = 0x1E02;
  17326. Engine._DECR = 0x1E03;
  17327. Engine._INVERT = 0x150A;
  17328. Engine._INCR_WRAP = 0x8507;
  17329. Engine._DECR_WRAP = 0x8508;
  17330. // Texture rescaling mode
  17331. Engine._SCALEMODE_FLOOR = 1;
  17332. Engine._SCALEMODE_NEAREST = 2;
  17333. Engine._SCALEMODE_CEILING = 3;
  17334. // Updatable statics so stick with vars here
  17335. /**
  17336. * Gets or sets the epsilon value used by collision engine
  17337. */
  17338. Engine.CollisionsEpsilon = 0.001;
  17339. /**
  17340. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17341. */
  17342. Engine.CodeRepository = "src/";
  17343. /**
  17344. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17345. */
  17346. Engine.ShadersRepository = "src/Shaders/";
  17347. return Engine;
  17348. }());
  17349. BABYLON.Engine = Engine;
  17350. })(BABYLON || (BABYLON = {}));
  17351. //# sourceMappingURL=babylon.engine.js.map
  17352. var BABYLON;
  17353. (function (BABYLON) {
  17354. /**
  17355. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17356. */
  17357. var Node = /** @class */ (function () {
  17358. /**
  17359. * Creates a new Node
  17360. * @param {string} name - the name and id to be given to this node
  17361. * @param {BABYLON.Scene} the scene this node will be added to
  17362. */
  17363. function Node(name, scene) {
  17364. if (scene === void 0) { scene = null; }
  17365. /**
  17366. * Gets or sets a string used to store user defined state for the node
  17367. */
  17368. this.state = "";
  17369. /**
  17370. * Gets or sets an object used to store user defined information for the node
  17371. */
  17372. this.metadata = null;
  17373. /**
  17374. * Gets or sets a boolean used to define if the node must be serialized
  17375. */
  17376. this.doNotSerialize = false;
  17377. /** @hidden */
  17378. this._isDisposed = false;
  17379. /**
  17380. * Gets a list of Animations associated with the node
  17381. */
  17382. this.animations = new Array();
  17383. this._ranges = {};
  17384. this._isEnabled = true;
  17385. this._isReady = true;
  17386. /** @hidden */
  17387. this._currentRenderId = -1;
  17388. this._parentRenderId = -1;
  17389. this._childRenderId = -1;
  17390. this._animationPropertiesOverride = null;
  17391. /**
  17392. * An event triggered when the mesh is disposed
  17393. */
  17394. this.onDisposeObservable = new BABYLON.Observable();
  17395. // Behaviors
  17396. this._behaviors = new Array();
  17397. this.name = name;
  17398. this.id = name;
  17399. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17400. this.uniqueId = this._scene.getUniqueId();
  17401. this._initCache();
  17402. }
  17403. /**
  17404. * Gets a boolean indicating if the node has been disposed
  17405. * @returns true if the node was disposed
  17406. */
  17407. Node.prototype.isDisposed = function () {
  17408. return this._isDisposed;
  17409. };
  17410. Object.defineProperty(Node.prototype, "parent", {
  17411. get: function () {
  17412. return this._parentNode;
  17413. },
  17414. /**
  17415. * Gets or sets the parent of the node
  17416. */
  17417. set: function (parent) {
  17418. if (this._parentNode === parent) {
  17419. return;
  17420. }
  17421. // Remove self from list of children of parent
  17422. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17423. var index = this._parentNode._children.indexOf(this);
  17424. if (index !== -1) {
  17425. this._parentNode._children.splice(index, 1);
  17426. }
  17427. }
  17428. // Store new parent
  17429. this._parentNode = parent;
  17430. // Add as child to new parent
  17431. if (this._parentNode) {
  17432. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17433. this._parentNode._children = new Array();
  17434. }
  17435. this._parentNode._children.push(this);
  17436. }
  17437. },
  17438. enumerable: true,
  17439. configurable: true
  17440. });
  17441. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17442. /**
  17443. * Gets or sets the animation properties override
  17444. */
  17445. get: function () {
  17446. if (!this._animationPropertiesOverride) {
  17447. return this._scene.animationPropertiesOverride;
  17448. }
  17449. return this._animationPropertiesOverride;
  17450. },
  17451. set: function (value) {
  17452. this._animationPropertiesOverride = value;
  17453. },
  17454. enumerable: true,
  17455. configurable: true
  17456. });
  17457. /**
  17458. * Gets a string idenfifying the name of the class
  17459. * @returns "Node" string
  17460. */
  17461. Node.prototype.getClassName = function () {
  17462. return "Node";
  17463. };
  17464. Object.defineProperty(Node.prototype, "onDispose", {
  17465. /**
  17466. * Sets a callback that will be raised when the node will be disposed
  17467. */
  17468. set: function (callback) {
  17469. if (this._onDisposeObserver) {
  17470. this.onDisposeObservable.remove(this._onDisposeObserver);
  17471. }
  17472. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17473. },
  17474. enumerable: true,
  17475. configurable: true
  17476. });
  17477. /**
  17478. * Gets the scene of the node
  17479. * @returns a {BABYLON.Scene}
  17480. */
  17481. Node.prototype.getScene = function () {
  17482. return this._scene;
  17483. };
  17484. /**
  17485. * Gets the engine of the node
  17486. * @returns a {BABYLON.Engine}
  17487. */
  17488. Node.prototype.getEngine = function () {
  17489. return this._scene.getEngine();
  17490. };
  17491. /**
  17492. * Attach a behavior to the node
  17493. * @see http://doc.babylonjs.com/features/behaviour
  17494. * @param behavior defines the behavior to attach
  17495. * @returns the current Node
  17496. */
  17497. Node.prototype.addBehavior = function (behavior) {
  17498. var _this = this;
  17499. var index = this._behaviors.indexOf(behavior);
  17500. if (index !== -1) {
  17501. return this;
  17502. }
  17503. behavior.init();
  17504. if (this._scene.isLoading) {
  17505. // We defer the attach when the scene will be loaded
  17506. var observer = this._scene.onDataLoadedObservable.add(function () {
  17507. behavior.attach(_this);
  17508. setTimeout(function () {
  17509. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  17510. _this._scene.onDataLoadedObservable.remove(observer);
  17511. }, 0);
  17512. });
  17513. }
  17514. else {
  17515. behavior.attach(this);
  17516. }
  17517. this._behaviors.push(behavior);
  17518. return this;
  17519. };
  17520. /**
  17521. * Remove an attached behavior
  17522. * @see http://doc.babylonjs.com/features/behaviour
  17523. * @param behavior defines the behavior to attach
  17524. * @returns the current Node
  17525. */
  17526. Node.prototype.removeBehavior = function (behavior) {
  17527. var index = this._behaviors.indexOf(behavior);
  17528. if (index === -1) {
  17529. return this;
  17530. }
  17531. this._behaviors[index].detach();
  17532. this._behaviors.splice(index, 1);
  17533. return this;
  17534. };
  17535. Object.defineProperty(Node.prototype, "behaviors", {
  17536. /**
  17537. * Gets the list of attached behaviors
  17538. * @see http://doc.babylonjs.com/features/behaviour
  17539. */
  17540. get: function () {
  17541. return this._behaviors;
  17542. },
  17543. enumerable: true,
  17544. configurable: true
  17545. });
  17546. /**
  17547. * Gets an attached behavior by name
  17548. * @param name defines the name of the behavior to look for
  17549. * @see http://doc.babylonjs.com/features/behaviour
  17550. * @returns null if behavior was not found else the requested behavior
  17551. */
  17552. Node.prototype.getBehaviorByName = function (name) {
  17553. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17554. var behavior = _a[_i];
  17555. if (behavior.name === name) {
  17556. return behavior;
  17557. }
  17558. }
  17559. return null;
  17560. };
  17561. /**
  17562. * Returns the world matrix of the node
  17563. * @returns a matrix containing the node's world matrix
  17564. */
  17565. Node.prototype.getWorldMatrix = function () {
  17566. return BABYLON.Matrix.Identity();
  17567. };
  17568. /** @hidden */
  17569. Node.prototype._getWorldMatrixDeterminant = function () {
  17570. return 1;
  17571. };
  17572. // override it in derived class if you add new variables to the cache
  17573. // and call the parent class method
  17574. /** @hidden */
  17575. Node.prototype._initCache = function () {
  17576. this._cache = {};
  17577. this._cache.parent = undefined;
  17578. };
  17579. /** @hidden */
  17580. Node.prototype.updateCache = function (force) {
  17581. if (!force && this.isSynchronized())
  17582. return;
  17583. this._cache.parent = this.parent;
  17584. this._updateCache();
  17585. };
  17586. // override it in derived class if you add new variables to the cache
  17587. // and call the parent class method if !ignoreParentClass
  17588. /** @hidden */
  17589. Node.prototype._updateCache = function (ignoreParentClass) {
  17590. };
  17591. // override it in derived class if you add new variables to the cache
  17592. /** @hidden */
  17593. Node.prototype._isSynchronized = function () {
  17594. return true;
  17595. };
  17596. /** @hidden */
  17597. Node.prototype._markSyncedWithParent = function () {
  17598. if (this.parent) {
  17599. this._parentRenderId = this.parent._childRenderId;
  17600. }
  17601. };
  17602. /** @hidden */
  17603. Node.prototype.isSynchronizedWithParent = function () {
  17604. if (!this.parent) {
  17605. return true;
  17606. }
  17607. if (this._parentRenderId !== this.parent._childRenderId) {
  17608. return false;
  17609. }
  17610. return this.parent.isSynchronized();
  17611. };
  17612. /** @hidden */
  17613. Node.prototype.isSynchronized = function (updateCache) {
  17614. var check = this.hasNewParent();
  17615. check = check || !this.isSynchronizedWithParent();
  17616. check = check || !this._isSynchronized();
  17617. if (updateCache)
  17618. this.updateCache(true);
  17619. return !check;
  17620. };
  17621. /** @hidden */
  17622. Node.prototype.hasNewParent = function (update) {
  17623. if (this._cache.parent === this.parent)
  17624. return false;
  17625. if (update)
  17626. this._cache.parent = this.parent;
  17627. return true;
  17628. };
  17629. /**
  17630. * Is this node ready to be used/rendered
  17631. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17632. * @return true if the node is ready
  17633. */
  17634. Node.prototype.isReady = function (completeCheck) {
  17635. if (completeCheck === void 0) { completeCheck = false; }
  17636. return this._isReady;
  17637. };
  17638. /**
  17639. * Is this node enabled?
  17640. * 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
  17641. * @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
  17642. * @return whether this node (and its parent) is enabled
  17643. */
  17644. Node.prototype.isEnabled = function (checkAncestors) {
  17645. if (checkAncestors === void 0) { checkAncestors = true; }
  17646. if (checkAncestors === false) {
  17647. return this._isEnabled;
  17648. }
  17649. if (this._isEnabled === false) {
  17650. return false;
  17651. }
  17652. if (this.parent !== undefined && this.parent !== null) {
  17653. return this.parent.isEnabled(checkAncestors);
  17654. }
  17655. return true;
  17656. };
  17657. /**
  17658. * Set the enabled state of this node
  17659. * @param value defines the new enabled state
  17660. */
  17661. Node.prototype.setEnabled = function (value) {
  17662. this._isEnabled = value;
  17663. };
  17664. /**
  17665. * Is this node a descendant of the given node?
  17666. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17667. * @param ancestor defines the parent node to inspect
  17668. * @returns a boolean indicating if this node is a descendant of the given node
  17669. */
  17670. Node.prototype.isDescendantOf = function (ancestor) {
  17671. if (this.parent) {
  17672. if (this.parent === ancestor) {
  17673. return true;
  17674. }
  17675. return this.parent.isDescendantOf(ancestor);
  17676. }
  17677. return false;
  17678. };
  17679. /** @hidden */
  17680. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17681. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17682. if (!this._children) {
  17683. return;
  17684. }
  17685. for (var index = 0; index < this._children.length; index++) {
  17686. var item = this._children[index];
  17687. if (!predicate || predicate(item)) {
  17688. results.push(item);
  17689. }
  17690. if (!directDescendantsOnly) {
  17691. item._getDescendants(results, false, predicate);
  17692. }
  17693. }
  17694. };
  17695. /**
  17696. * Will return all nodes that have this node as ascendant
  17697. * @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
  17698. * @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
  17699. * @return all children nodes of all types
  17700. */
  17701. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  17702. var results = new Array();
  17703. this._getDescendants(results, directDescendantsOnly, predicate);
  17704. return results;
  17705. };
  17706. /**
  17707. * Get all child-meshes of this node
  17708. * @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
  17709. * @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
  17710. * @returns an array of {BABYLON.AbstractMesh}
  17711. */
  17712. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  17713. var results = [];
  17714. this._getDescendants(results, directDescendantsOnly, function (node) {
  17715. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  17716. });
  17717. return results;
  17718. };
  17719. /**
  17720. * Get all child-transformNodes of this node
  17721. * @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
  17722. * @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
  17723. * @returns an array of {BABYLON.TransformNode}
  17724. */
  17725. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  17726. var results = [];
  17727. this._getDescendants(results, directDescendantsOnly, function (node) {
  17728. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  17729. });
  17730. return results;
  17731. };
  17732. /**
  17733. * Get all direct children of this node
  17734. * @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
  17735. * @returns an array of {BABYLON.Node}
  17736. */
  17737. Node.prototype.getChildren = function (predicate) {
  17738. return this.getDescendants(true, predicate);
  17739. };
  17740. /** @hidden */
  17741. Node.prototype._setReady = function (state) {
  17742. if (state === this._isReady) {
  17743. return;
  17744. }
  17745. if (!state) {
  17746. this._isReady = false;
  17747. return;
  17748. }
  17749. if (this.onReady) {
  17750. this.onReady(this);
  17751. }
  17752. this._isReady = true;
  17753. };
  17754. /**
  17755. * Get an animation by name
  17756. * @param name defines the name of the animation to look for
  17757. * @returns null if not found else the requested animation
  17758. */
  17759. Node.prototype.getAnimationByName = function (name) {
  17760. for (var i = 0; i < this.animations.length; i++) {
  17761. var animation = this.animations[i];
  17762. if (animation.name === name) {
  17763. return animation;
  17764. }
  17765. }
  17766. return null;
  17767. };
  17768. /**
  17769. * Creates an animation range for this node
  17770. * @param name defines the name of the range
  17771. * @param from defines the starting key
  17772. * @param to defines the end key
  17773. */
  17774. Node.prototype.createAnimationRange = function (name, from, to) {
  17775. // check name not already in use
  17776. if (!this._ranges[name]) {
  17777. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  17778. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17779. if (this.animations[i]) {
  17780. this.animations[i].createRange(name, from, to);
  17781. }
  17782. }
  17783. }
  17784. };
  17785. /**
  17786. * Delete a specific animation range
  17787. * @param name defines the name of the range to delete
  17788. * @param deleteFrames defines if animation frames from the range must be deleted as well
  17789. */
  17790. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  17791. if (deleteFrames === void 0) { deleteFrames = true; }
  17792. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17793. if (this.animations[i]) {
  17794. this.animations[i].deleteRange(name, deleteFrames);
  17795. }
  17796. }
  17797. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  17798. };
  17799. /**
  17800. * Get an animation range by name
  17801. * @param name defines the name of the animation range to look for
  17802. * @returns null if not found else the requested animation range
  17803. */
  17804. Node.prototype.getAnimationRange = function (name) {
  17805. return this._ranges[name];
  17806. };
  17807. /**
  17808. * Will start the animation sequence
  17809. * @param name defines the range frames for animation sequence
  17810. * @param loop defines if the animation should loop (false by default)
  17811. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  17812. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  17813. * @returns the object created for this animation. If range does not exist, it will return null
  17814. */
  17815. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  17816. var range = this.getAnimationRange(name);
  17817. if (!range) {
  17818. return null;
  17819. }
  17820. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  17821. };
  17822. /**
  17823. * Serialize animation ranges into a JSON compatible object
  17824. * @returns serialization object
  17825. */
  17826. Node.prototype.serializeAnimationRanges = function () {
  17827. var serializationRanges = [];
  17828. for (var name in this._ranges) {
  17829. var localRange = this._ranges[name];
  17830. if (!localRange) {
  17831. continue;
  17832. }
  17833. var range = {};
  17834. range.name = name;
  17835. range.from = localRange.from;
  17836. range.to = localRange.to;
  17837. serializationRanges.push(range);
  17838. }
  17839. return serializationRanges;
  17840. };
  17841. /**
  17842. * Computes the world matrix of the node
  17843. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  17844. * @returns the world matrix
  17845. */
  17846. Node.prototype.computeWorldMatrix = function (force) {
  17847. return BABYLON.Matrix.Identity();
  17848. };
  17849. /**
  17850. * Releases resources associated with this node.
  17851. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17852. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17853. */
  17854. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17855. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17856. if (!doNotRecurse) {
  17857. var nodes = this.getDescendants(true);
  17858. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  17859. var node = nodes_1[_i];
  17860. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  17861. }
  17862. }
  17863. else {
  17864. var transformNodes = this.getChildTransformNodes(true);
  17865. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  17866. var transformNode = transformNodes_1[_a];
  17867. transformNode.parent = null;
  17868. transformNode.computeWorldMatrix(true);
  17869. }
  17870. }
  17871. this.parent = null;
  17872. // Callback
  17873. this.onDisposeObservable.notifyObservers(this);
  17874. this.onDisposeObservable.clear();
  17875. // Behaviors
  17876. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  17877. var behavior = _c[_b];
  17878. behavior.detach();
  17879. }
  17880. this._behaviors = [];
  17881. this._isDisposed = true;
  17882. };
  17883. /**
  17884. * Parse animation range data from a serialization object and store them into a given node
  17885. * @param node defines where to store the animation ranges
  17886. * @param parsedNode defines the serialization object to read data from
  17887. * @param scene defines the hosting scene
  17888. */
  17889. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  17890. if (parsedNode.ranges) {
  17891. for (var index = 0; index < parsedNode.ranges.length; index++) {
  17892. var data = parsedNode.ranges[index];
  17893. node.createAnimationRange(data.name, data.from, data.to);
  17894. }
  17895. }
  17896. };
  17897. __decorate([
  17898. BABYLON.serialize()
  17899. ], Node.prototype, "name", void 0);
  17900. __decorate([
  17901. BABYLON.serialize()
  17902. ], Node.prototype, "id", void 0);
  17903. __decorate([
  17904. BABYLON.serialize()
  17905. ], Node.prototype, "uniqueId", void 0);
  17906. __decorate([
  17907. BABYLON.serialize()
  17908. ], Node.prototype, "state", void 0);
  17909. __decorate([
  17910. BABYLON.serialize()
  17911. ], Node.prototype, "metadata", void 0);
  17912. return Node;
  17913. }());
  17914. BABYLON.Node = Node;
  17915. })(BABYLON || (BABYLON = {}));
  17916. //# sourceMappingURL=babylon.node.js.map
  17917. var BABYLON;
  17918. (function (BABYLON) {
  17919. var BoundingSphere = /** @class */ (function () {
  17920. /**
  17921. * Creates a new bounding sphere
  17922. * @param min defines the minimum vector (in local space)
  17923. * @param max defines the maximum vector (in local space)
  17924. */
  17925. function BoundingSphere(min, max) {
  17926. this._tempRadiusVector = BABYLON.Vector3.Zero();
  17927. this.reConstruct(min, max);
  17928. }
  17929. /**
  17930. * Recreates the entire bounding sphere from scratch
  17931. * @param min defines the new minimum vector (in local space)
  17932. * @param max defines the new maximum vector (in local space)
  17933. */
  17934. BoundingSphere.prototype.reConstruct = function (min, max) {
  17935. this.minimum = min.clone();
  17936. this.maximum = max.clone();
  17937. var distance = BABYLON.Vector3.Distance(min, max);
  17938. this.center = BABYLON.Vector3.Lerp(min, max, 0.5);
  17939. this.radius = distance * 0.5;
  17940. this.centerWorld = BABYLON.Vector3.Zero();
  17941. this._update(BABYLON.Matrix.Identity());
  17942. };
  17943. // Methods
  17944. BoundingSphere.prototype._update = function (world) {
  17945. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  17946. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  17947. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  17948. };
  17949. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  17950. for (var i = 0; i < 6; i++) {
  17951. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  17952. return false;
  17953. }
  17954. return true;
  17955. };
  17956. BoundingSphere.prototype.intersectsPoint = function (point) {
  17957. var x = this.centerWorld.x - point.x;
  17958. var y = this.centerWorld.y - point.y;
  17959. var z = this.centerWorld.z - point.z;
  17960. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  17961. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  17962. return false;
  17963. return true;
  17964. };
  17965. // Statics
  17966. BoundingSphere.Intersects = function (sphere0, sphere1) {
  17967. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  17968. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  17969. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  17970. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  17971. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  17972. return false;
  17973. return true;
  17974. };
  17975. return BoundingSphere;
  17976. }());
  17977. BABYLON.BoundingSphere = BoundingSphere;
  17978. })(BABYLON || (BABYLON = {}));
  17979. //# sourceMappingURL=babylon.boundingSphere.js.map
  17980. var BABYLON;
  17981. (function (BABYLON) {
  17982. var BoundingBox = /** @class */ (function () {
  17983. /**
  17984. * Creates a new bounding box
  17985. * @param min defines the minimum vector (in local space)
  17986. * @param max defines the maximum vector (in local space)
  17987. */
  17988. function BoundingBox(min, max) {
  17989. this.vectorsWorld = new Array();
  17990. this.reConstruct(min, max);
  17991. }
  17992. // Methods
  17993. /**
  17994. * Recreates the entire bounding box from scratch
  17995. * @param min defines the new minimum vector (in local space)
  17996. * @param max defines the new maximum vector (in local space)
  17997. */
  17998. BoundingBox.prototype.reConstruct = function (min, max) {
  17999. this.minimum = min.clone();
  18000. this.maximum = max.clone();
  18001. // Bounding vectors
  18002. this.vectors = new Array();
  18003. this.vectors.push(this.minimum.clone());
  18004. this.vectors.push(this.maximum.clone());
  18005. this.vectors.push(this.minimum.clone());
  18006. this.vectors[2].x = this.maximum.x;
  18007. this.vectors.push(this.minimum.clone());
  18008. this.vectors[3].y = this.maximum.y;
  18009. this.vectors.push(this.minimum.clone());
  18010. this.vectors[4].z = this.maximum.z;
  18011. this.vectors.push(this.maximum.clone());
  18012. this.vectors[5].z = this.minimum.z;
  18013. this.vectors.push(this.maximum.clone());
  18014. this.vectors[6].x = this.minimum.x;
  18015. this.vectors.push(this.maximum.clone());
  18016. this.vectors[7].y = this.minimum.y;
  18017. // OBB
  18018. this.center = this.maximum.add(this.minimum).scale(0.5);
  18019. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  18020. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18021. // World
  18022. for (var index = 0; index < this.vectors.length; index++) {
  18023. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  18024. }
  18025. this.minimumWorld = BABYLON.Vector3.Zero();
  18026. this.maximumWorld = BABYLON.Vector3.Zero();
  18027. this.centerWorld = BABYLON.Vector3.Zero();
  18028. this.extendSizeWorld = BABYLON.Vector3.Zero();
  18029. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  18030. };
  18031. BoundingBox.prototype.getWorldMatrix = function () {
  18032. return this._worldMatrix;
  18033. };
  18034. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18035. this._worldMatrix.copyFrom(matrix);
  18036. return this;
  18037. };
  18038. BoundingBox.prototype._update = function (world) {
  18039. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18040. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18041. for (var index = 0; index < this.vectors.length; index++) {
  18042. var v = this.vectorsWorld[index];
  18043. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18044. if (v.x < this.minimumWorld.x)
  18045. this.minimumWorld.x = v.x;
  18046. if (v.y < this.minimumWorld.y)
  18047. this.minimumWorld.y = v.y;
  18048. if (v.z < this.minimumWorld.z)
  18049. this.minimumWorld.z = v.z;
  18050. if (v.x > this.maximumWorld.x)
  18051. this.maximumWorld.x = v.x;
  18052. if (v.y > this.maximumWorld.y)
  18053. this.maximumWorld.y = v.y;
  18054. if (v.z > this.maximumWorld.z)
  18055. this.maximumWorld.z = v.z;
  18056. }
  18057. // Extend
  18058. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18059. this.extendSizeWorld.scaleInPlace(0.5);
  18060. // OBB
  18061. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18062. this.centerWorld.scaleInPlace(0.5);
  18063. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18064. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18065. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18066. this._worldMatrix = world;
  18067. };
  18068. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18069. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18070. };
  18071. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18072. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18073. };
  18074. BoundingBox.prototype.intersectsPoint = function (point) {
  18075. var delta = -BABYLON.Epsilon;
  18076. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18077. return false;
  18078. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18079. return false;
  18080. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18081. return false;
  18082. return true;
  18083. };
  18084. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18085. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18086. };
  18087. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18088. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18089. return false;
  18090. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18091. return false;
  18092. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18093. return false;
  18094. return true;
  18095. };
  18096. // Statics
  18097. BoundingBox.Intersects = function (box0, box1) {
  18098. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18099. return false;
  18100. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18101. return false;
  18102. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18103. return false;
  18104. return true;
  18105. };
  18106. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18107. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18108. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18109. return (num <= (sphereRadius * sphereRadius));
  18110. };
  18111. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18112. for (var p = 0; p < 6; p++) {
  18113. for (var i = 0; i < 8; i++) {
  18114. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18115. return false;
  18116. }
  18117. }
  18118. }
  18119. return true;
  18120. };
  18121. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18122. for (var p = 0; p < 6; p++) {
  18123. var inCount = 8;
  18124. for (var i = 0; i < 8; i++) {
  18125. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18126. --inCount;
  18127. }
  18128. else {
  18129. break;
  18130. }
  18131. }
  18132. if (inCount === 0)
  18133. return false;
  18134. }
  18135. return true;
  18136. };
  18137. return BoundingBox;
  18138. }());
  18139. BABYLON.BoundingBox = BoundingBox;
  18140. })(BABYLON || (BABYLON = {}));
  18141. //# sourceMappingURL=babylon.boundingBox.js.map
  18142. var BABYLON;
  18143. (function (BABYLON) {
  18144. var computeBoxExtents = function (axis, box) {
  18145. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18146. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18147. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18148. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18149. var r = r0 + r1 + r2;
  18150. return {
  18151. min: p - r,
  18152. max: p + r
  18153. };
  18154. };
  18155. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18156. var axisOverlap = function (axis, box0, box1) {
  18157. var result0 = computeBoxExtents(axis, box0);
  18158. var result1 = computeBoxExtents(axis, box1);
  18159. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18160. };
  18161. var BoundingInfo = /** @class */ (function () {
  18162. function BoundingInfo(minimum, maximum) {
  18163. this.minimum = minimum;
  18164. this.maximum = maximum;
  18165. this._isLocked = false;
  18166. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18167. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18168. }
  18169. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18170. get: function () {
  18171. return this._isLocked;
  18172. },
  18173. set: function (value) {
  18174. this._isLocked = value;
  18175. },
  18176. enumerable: true,
  18177. configurable: true
  18178. });
  18179. // Methods
  18180. BoundingInfo.prototype.update = function (world) {
  18181. if (this._isLocked) {
  18182. return;
  18183. }
  18184. this.boundingBox._update(world);
  18185. this.boundingSphere._update(world);
  18186. };
  18187. /**
  18188. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18189. * @param center New center of the bounding info
  18190. * @param extend New extend of the bounding info
  18191. */
  18192. BoundingInfo.prototype.centerOn = function (center, extend) {
  18193. this.minimum = center.subtract(extend);
  18194. this.maximum = center.add(extend);
  18195. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18196. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18197. return this;
  18198. };
  18199. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  18200. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  18201. return false;
  18202. return this.boundingBox.isInFrustum(frustumPlanes);
  18203. };
  18204. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18205. /**
  18206. * Gets the world distance between the min and max points of the bounding box
  18207. */
  18208. get: function () {
  18209. var boundingBox = this.boundingBox;
  18210. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18211. return size.length();
  18212. },
  18213. enumerable: true,
  18214. configurable: true
  18215. });
  18216. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18217. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18218. };
  18219. BoundingInfo.prototype._checkCollision = function (collider) {
  18220. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18221. };
  18222. BoundingInfo.prototype.intersectsPoint = function (point) {
  18223. if (!this.boundingSphere.centerWorld) {
  18224. return false;
  18225. }
  18226. if (!this.boundingSphere.intersectsPoint(point)) {
  18227. return false;
  18228. }
  18229. if (!this.boundingBox.intersectsPoint(point)) {
  18230. return false;
  18231. }
  18232. return true;
  18233. };
  18234. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18235. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18236. return false;
  18237. }
  18238. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18239. return false;
  18240. }
  18241. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18242. return false;
  18243. }
  18244. if (!precise) {
  18245. return true;
  18246. }
  18247. var box0 = this.boundingBox;
  18248. var box1 = boundingInfo.boundingBox;
  18249. if (!axisOverlap(box0.directions[0], box0, box1))
  18250. return false;
  18251. if (!axisOverlap(box0.directions[1], box0, box1))
  18252. return false;
  18253. if (!axisOverlap(box0.directions[2], box0, box1))
  18254. return false;
  18255. if (!axisOverlap(box1.directions[0], box0, box1))
  18256. return false;
  18257. if (!axisOverlap(box1.directions[1], box0, box1))
  18258. return false;
  18259. if (!axisOverlap(box1.directions[2], box0, box1))
  18260. return false;
  18261. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18262. return false;
  18263. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18264. return false;
  18265. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18266. return false;
  18267. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18268. return false;
  18269. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18270. return false;
  18271. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18272. return false;
  18273. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18274. return false;
  18275. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18276. return false;
  18277. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18278. return false;
  18279. return true;
  18280. };
  18281. return BoundingInfo;
  18282. }());
  18283. BABYLON.BoundingInfo = BoundingInfo;
  18284. })(BABYLON || (BABYLON = {}));
  18285. //# sourceMappingURL=babylon.boundingInfo.js.map
  18286. var BABYLON;
  18287. (function (BABYLON) {
  18288. var TransformNode = /** @class */ (function (_super) {
  18289. __extends(TransformNode, _super);
  18290. function TransformNode(name, scene, isPure) {
  18291. if (scene === void 0) { scene = null; }
  18292. if (isPure === void 0) { isPure = true; }
  18293. var _this = _super.call(this, name, scene) || this;
  18294. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18295. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18296. _this._up = new BABYLON.Vector3(0, 1, 0);
  18297. _this._right = new BABYLON.Vector3(1, 0, 0);
  18298. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18299. // Properties
  18300. _this._rotation = BABYLON.Vector3.Zero();
  18301. _this._scaling = BABYLON.Vector3.One();
  18302. _this._isDirty = false;
  18303. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18304. _this.scalingDeterminant = 1;
  18305. _this.infiniteDistance = false;
  18306. _this.position = BABYLON.Vector3.Zero();
  18307. _this._localWorld = BABYLON.Matrix.Zero();
  18308. _this._worldMatrix = BABYLON.Matrix.Zero();
  18309. _this._worldMatrixDeterminant = 0;
  18310. _this._absolutePosition = BABYLON.Vector3.Zero();
  18311. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18312. _this._postMultiplyPivotMatrix = false;
  18313. _this._isWorldMatrixFrozen = false;
  18314. /**
  18315. * An event triggered after the world matrix is updated
  18316. */
  18317. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18318. _this._nonUniformScaling = false;
  18319. if (isPure) {
  18320. _this.getScene().addTransformNode(_this);
  18321. }
  18322. return _this;
  18323. }
  18324. /**
  18325. * Gets a string idenfifying the name of the class
  18326. * @returns "TransformNode" string
  18327. */
  18328. TransformNode.prototype.getClassName = function () {
  18329. return "TransformNode";
  18330. };
  18331. Object.defineProperty(TransformNode.prototype, "rotation", {
  18332. /**
  18333. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18334. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18335. * Default : (0.0, 0.0, 0.0)
  18336. */
  18337. get: function () {
  18338. return this._rotation;
  18339. },
  18340. set: function (newRotation) {
  18341. this._rotation = newRotation;
  18342. },
  18343. enumerable: true,
  18344. configurable: true
  18345. });
  18346. Object.defineProperty(TransformNode.prototype, "scaling", {
  18347. /**
  18348. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18349. * Default : (1.0, 1.0, 1.0)
  18350. */
  18351. get: function () {
  18352. return this._scaling;
  18353. },
  18354. /**
  18355. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18356. * Default : (1.0, 1.0, 1.0)
  18357. */
  18358. set: function (newScaling) {
  18359. this._scaling = newScaling;
  18360. },
  18361. enumerable: true,
  18362. configurable: true
  18363. });
  18364. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18365. /**
  18366. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18367. * It's null by default.
  18368. * 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)
  18369. */
  18370. get: function () {
  18371. return this._rotationQuaternion;
  18372. },
  18373. set: function (quaternion) {
  18374. this._rotationQuaternion = quaternion;
  18375. //reset the rotation vector.
  18376. if (quaternion && this.rotation.length()) {
  18377. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18378. }
  18379. },
  18380. enumerable: true,
  18381. configurable: true
  18382. });
  18383. Object.defineProperty(TransformNode.prototype, "forward", {
  18384. /**
  18385. * The forward direction of that transform in world space.
  18386. */
  18387. get: function () {
  18388. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18389. },
  18390. enumerable: true,
  18391. configurable: true
  18392. });
  18393. Object.defineProperty(TransformNode.prototype, "up", {
  18394. /**
  18395. * The up direction of that transform in world space.
  18396. */
  18397. get: function () {
  18398. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18399. },
  18400. enumerable: true,
  18401. configurable: true
  18402. });
  18403. Object.defineProperty(TransformNode.prototype, "right", {
  18404. /**
  18405. * The right direction of that transform in world space.
  18406. */
  18407. get: function () {
  18408. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18409. },
  18410. enumerable: true,
  18411. configurable: true
  18412. });
  18413. /**
  18414. * Returns the latest update of the World matrix
  18415. * Returns a Matrix.
  18416. */
  18417. TransformNode.prototype.getWorldMatrix = function () {
  18418. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18419. this.computeWorldMatrix();
  18420. }
  18421. return this._worldMatrix;
  18422. };
  18423. /** @hidden */
  18424. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18425. return this._worldMatrixDeterminant;
  18426. };
  18427. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18428. /**
  18429. * Returns directly the latest state of the mesh World matrix.
  18430. * A Matrix is returned.
  18431. */
  18432. get: function () {
  18433. return this._worldMatrix;
  18434. },
  18435. enumerable: true,
  18436. configurable: true
  18437. });
  18438. /**
  18439. * Copies the paramater passed Matrix into the mesh Pose matrix.
  18440. * Returns the TransformNode.
  18441. */
  18442. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18443. this._poseMatrix.copyFrom(matrix);
  18444. return this;
  18445. };
  18446. /**
  18447. * Returns the mesh Pose matrix.
  18448. * Returned object : Matrix
  18449. */
  18450. TransformNode.prototype.getPoseMatrix = function () {
  18451. return this._poseMatrix;
  18452. };
  18453. TransformNode.prototype._isSynchronized = function () {
  18454. if (this._isDirty) {
  18455. return false;
  18456. }
  18457. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18458. return false;
  18459. if (this._cache.pivotMatrixUpdated) {
  18460. return false;
  18461. }
  18462. if (this.infiniteDistance) {
  18463. return false;
  18464. }
  18465. if (!this._cache.position.equals(this.position))
  18466. return false;
  18467. if (this.rotationQuaternion) {
  18468. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  18469. return false;
  18470. }
  18471. if (!this._cache.rotation.equals(this.rotation))
  18472. return false;
  18473. if (!this._cache.scaling.equals(this.scaling))
  18474. return false;
  18475. return true;
  18476. };
  18477. TransformNode.prototype._initCache = function () {
  18478. _super.prototype._initCache.call(this);
  18479. this._cache.localMatrixUpdated = false;
  18480. this._cache.position = BABYLON.Vector3.Zero();
  18481. this._cache.scaling = BABYLON.Vector3.Zero();
  18482. this._cache.rotation = BABYLON.Vector3.Zero();
  18483. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18484. this._cache.billboardMode = -1;
  18485. };
  18486. TransformNode.prototype.markAsDirty = function (property) {
  18487. if (property === "rotation") {
  18488. this.rotationQuaternion = null;
  18489. }
  18490. this._currentRenderId = Number.MAX_VALUE;
  18491. this._isDirty = true;
  18492. return this;
  18493. };
  18494. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18495. /**
  18496. * Returns the current mesh absolute position.
  18497. * Retuns a Vector3.
  18498. */
  18499. get: function () {
  18500. return this._absolutePosition;
  18501. },
  18502. enumerable: true,
  18503. configurable: true
  18504. });
  18505. /**
  18506. * Sets a new matrix to apply before all other transformation
  18507. * @param matrix defines the transform matrix
  18508. * @returns the current TransformNode
  18509. */
  18510. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18511. return this.setPivotMatrix(matrix, false);
  18512. };
  18513. /**
  18514. * Sets a new pivot matrix to the current node
  18515. * @param matrix defines the new pivot matrix to use
  18516. * @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
  18517. * @returns the current TransformNode
  18518. */
  18519. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18520. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18521. this._pivotMatrix = matrix.clone();
  18522. this._cache.pivotMatrixUpdated = true;
  18523. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18524. if (this._postMultiplyPivotMatrix) {
  18525. if (!this._pivotMatrixInverse) {
  18526. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18527. }
  18528. else {
  18529. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18530. }
  18531. }
  18532. return this;
  18533. };
  18534. /**
  18535. * Returns the mesh pivot matrix.
  18536. * Default : Identity.
  18537. * A Matrix is returned.
  18538. */
  18539. TransformNode.prototype.getPivotMatrix = function () {
  18540. return this._pivotMatrix;
  18541. };
  18542. /**
  18543. * Prevents the World matrix to be computed any longer.
  18544. * Returns the TransformNode.
  18545. */
  18546. TransformNode.prototype.freezeWorldMatrix = function () {
  18547. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18548. this.computeWorldMatrix(true);
  18549. this._isWorldMatrixFrozen = true;
  18550. return this;
  18551. };
  18552. /**
  18553. * Allows back the World matrix computation.
  18554. * Returns the TransformNode.
  18555. */
  18556. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18557. this._isWorldMatrixFrozen = false;
  18558. this.computeWorldMatrix(true);
  18559. return this;
  18560. };
  18561. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18562. /**
  18563. * True if the World matrix has been frozen.
  18564. * Returns a boolean.
  18565. */
  18566. get: function () {
  18567. return this._isWorldMatrixFrozen;
  18568. },
  18569. enumerable: true,
  18570. configurable: true
  18571. });
  18572. /**
  18573. * Retuns the mesh absolute position in the World.
  18574. * Returns a Vector3.
  18575. */
  18576. TransformNode.prototype.getAbsolutePosition = function () {
  18577. this.computeWorldMatrix();
  18578. return this._absolutePosition;
  18579. };
  18580. /**
  18581. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18582. * Returns the TransformNode.
  18583. */
  18584. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18585. if (!absolutePosition) {
  18586. return this;
  18587. }
  18588. var absolutePositionX;
  18589. var absolutePositionY;
  18590. var absolutePositionZ;
  18591. if (absolutePosition.x === undefined) {
  18592. if (arguments.length < 3) {
  18593. return this;
  18594. }
  18595. absolutePositionX = arguments[0];
  18596. absolutePositionY = arguments[1];
  18597. absolutePositionZ = arguments[2];
  18598. }
  18599. else {
  18600. absolutePositionX = absolutePosition.x;
  18601. absolutePositionY = absolutePosition.y;
  18602. absolutePositionZ = absolutePosition.z;
  18603. }
  18604. if (this.parent) {
  18605. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18606. invertParentWorldMatrix.invert();
  18607. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18608. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18609. }
  18610. else {
  18611. this.position.x = absolutePositionX;
  18612. this.position.y = absolutePositionY;
  18613. this.position.z = absolutePositionZ;
  18614. }
  18615. return this;
  18616. };
  18617. /**
  18618. * Sets the mesh position in its local space.
  18619. * Returns the TransformNode.
  18620. */
  18621. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18622. this.computeWorldMatrix();
  18623. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18624. return this;
  18625. };
  18626. /**
  18627. * Returns the mesh position in the local space from the current World matrix values.
  18628. * Returns a new Vector3.
  18629. */
  18630. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18631. this.computeWorldMatrix();
  18632. var invLocalWorldMatrix = this._localWorld.clone();
  18633. invLocalWorldMatrix.invert();
  18634. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18635. };
  18636. /**
  18637. * Translates the mesh along the passed Vector3 in its local space.
  18638. * Returns the TransformNode.
  18639. */
  18640. TransformNode.prototype.locallyTranslate = function (vector3) {
  18641. this.computeWorldMatrix(true);
  18642. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18643. return this;
  18644. };
  18645. /**
  18646. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18647. * @param targetPoint the position (must be in same space as current mesh) to look at
  18648. * @param yawCor optional yaw (y-axis) correction in radians
  18649. * @param pitchCor optional pitch (x-axis) correction in radians
  18650. * @param rollCor optional roll (z-axis) correction in radians
  18651. * @param space the choosen space of the target
  18652. * @returns the TransformNode.
  18653. */
  18654. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  18655. if (yawCor === void 0) { yawCor = 0; }
  18656. if (pitchCor === void 0) { pitchCor = 0; }
  18657. if (rollCor === void 0) { rollCor = 0; }
  18658. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18659. var dv = TransformNode._lookAtVectorCache;
  18660. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  18661. targetPoint.subtractToRef(pos, dv);
  18662. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  18663. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  18664. var pitch = Math.atan2(dv.y, len);
  18665. if (this.rotationQuaternion) {
  18666. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  18667. }
  18668. else {
  18669. this.rotation.x = pitch + pitchCor;
  18670. this.rotation.y = yaw + yawCor;
  18671. this.rotation.z = rollCor;
  18672. }
  18673. return this;
  18674. };
  18675. /**
  18676. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  18677. * This Vector3 is expressed in the World space.
  18678. */
  18679. TransformNode.prototype.getDirection = function (localAxis) {
  18680. var result = BABYLON.Vector3.Zero();
  18681. this.getDirectionToRef(localAxis, result);
  18682. return result;
  18683. };
  18684. /**
  18685. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  18686. * localAxis is expressed in the mesh local space.
  18687. * result is computed in the Wordl space from the mesh World matrix.
  18688. * Returns the TransformNode.
  18689. */
  18690. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  18691. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18692. return this;
  18693. };
  18694. /**
  18695. * Sets a new pivot point to the current node
  18696. * @param point defines the new pivot point to use
  18697. * @param space defines if the point is in world or local space (local by default)
  18698. * @returns the current TransformNode
  18699. */
  18700. TransformNode.prototype.setPivotPoint = function (point, space) {
  18701. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18702. if (this.getScene().getRenderId() == 0) {
  18703. this.computeWorldMatrix(true);
  18704. }
  18705. var wm = this.getWorldMatrix();
  18706. if (space == BABYLON.Space.WORLD) {
  18707. var tmat = BABYLON.Tmp.Matrix[0];
  18708. wm.invertToRef(tmat);
  18709. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  18710. }
  18711. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  18712. };
  18713. /**
  18714. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  18715. */
  18716. TransformNode.prototype.getPivotPoint = function () {
  18717. var point = BABYLON.Vector3.Zero();
  18718. this.getPivotPointToRef(point);
  18719. return point;
  18720. };
  18721. /**
  18722. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  18723. * Returns the TransformNode.
  18724. */
  18725. TransformNode.prototype.getPivotPointToRef = function (result) {
  18726. result.x = -this._pivotMatrix.m[12];
  18727. result.y = -this._pivotMatrix.m[13];
  18728. result.z = -this._pivotMatrix.m[14];
  18729. return this;
  18730. };
  18731. /**
  18732. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  18733. */
  18734. TransformNode.prototype.getAbsolutePivotPoint = function () {
  18735. var point = BABYLON.Vector3.Zero();
  18736. this.getAbsolutePivotPointToRef(point);
  18737. return point;
  18738. };
  18739. /**
  18740. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  18741. * Returns the TransformNode.
  18742. */
  18743. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  18744. result.x = this._pivotMatrix.m[12];
  18745. result.y = this._pivotMatrix.m[13];
  18746. result.z = this._pivotMatrix.m[14];
  18747. this.getPivotPointToRef(result);
  18748. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  18749. return this;
  18750. };
  18751. /**
  18752. * Defines the passed node as the parent of the current node.
  18753. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  18754. * Returns the TransformNode.
  18755. */
  18756. TransformNode.prototype.setParent = function (node) {
  18757. if (node === null) {
  18758. var rotation = BABYLON.Tmp.Quaternion[0];
  18759. var position = BABYLON.Tmp.Vector3[0];
  18760. var scale = BABYLON.Tmp.Vector3[1];
  18761. if (this.parent && this.parent.computeWorldMatrix) {
  18762. this.parent.computeWorldMatrix(true);
  18763. }
  18764. this.computeWorldMatrix(true);
  18765. this.getWorldMatrix().decompose(scale, rotation, position);
  18766. if (this.rotationQuaternion) {
  18767. this.rotationQuaternion.copyFrom(rotation);
  18768. }
  18769. else {
  18770. rotation.toEulerAnglesToRef(this.rotation);
  18771. }
  18772. this.scaling.x = scale.x;
  18773. this.scaling.y = scale.y;
  18774. this.scaling.z = scale.z;
  18775. this.position.x = position.x;
  18776. this.position.y = position.y;
  18777. this.position.z = position.z;
  18778. }
  18779. else {
  18780. var rotation = BABYLON.Tmp.Quaternion[0];
  18781. var position = BABYLON.Tmp.Vector3[0];
  18782. var scale = BABYLON.Tmp.Vector3[1];
  18783. var diffMatrix = BABYLON.Tmp.Matrix[0];
  18784. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  18785. this.computeWorldMatrix(true);
  18786. node.computeWorldMatrix(true);
  18787. node.getWorldMatrix().invertToRef(invParentMatrix);
  18788. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  18789. diffMatrix.decompose(scale, rotation, position);
  18790. if (this.rotationQuaternion) {
  18791. this.rotationQuaternion.copyFrom(rotation);
  18792. }
  18793. else {
  18794. rotation.toEulerAnglesToRef(this.rotation);
  18795. }
  18796. this.position.x = position.x;
  18797. this.position.y = position.y;
  18798. this.position.z = position.z;
  18799. this.scaling.x = scale.x;
  18800. this.scaling.y = scale.y;
  18801. this.scaling.z = scale.z;
  18802. }
  18803. this.parent = node;
  18804. return this;
  18805. };
  18806. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  18807. get: function () {
  18808. return this._nonUniformScaling;
  18809. },
  18810. enumerable: true,
  18811. configurable: true
  18812. });
  18813. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  18814. if (this._nonUniformScaling === value) {
  18815. return false;
  18816. }
  18817. this._nonUniformScaling = true;
  18818. return true;
  18819. };
  18820. /**
  18821. * Attach the current TransformNode to another TransformNode associated with a bone
  18822. * @param bone Bone affecting the TransformNode
  18823. * @param affectedTransformNode TransformNode associated with the bone
  18824. */
  18825. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  18826. this._transformToBoneReferal = affectedTransformNode;
  18827. this.parent = bone;
  18828. if (bone.getWorldMatrix().determinant() < 0) {
  18829. this.scalingDeterminant *= -1;
  18830. }
  18831. return this;
  18832. };
  18833. TransformNode.prototype.detachFromBone = function () {
  18834. if (!this.parent) {
  18835. return this;
  18836. }
  18837. if (this.parent.getWorldMatrix().determinant() < 0) {
  18838. this.scalingDeterminant *= -1;
  18839. }
  18840. this._transformToBoneReferal = null;
  18841. this.parent = null;
  18842. return this;
  18843. };
  18844. /**
  18845. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  18846. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18847. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18848. * The passed axis is also normalized.
  18849. * Returns the TransformNode.
  18850. */
  18851. TransformNode.prototype.rotate = function (axis, amount, space) {
  18852. axis.normalize();
  18853. if (!this.rotationQuaternion) {
  18854. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18855. this.rotation = BABYLON.Vector3.Zero();
  18856. }
  18857. var rotationQuaternion;
  18858. if (!space || space === BABYLON.Space.LOCAL) {
  18859. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18860. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  18861. }
  18862. else {
  18863. if (this.parent) {
  18864. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18865. invertParentWorldMatrix.invert();
  18866. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  18867. }
  18868. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18869. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18870. }
  18871. return this;
  18872. };
  18873. /**
  18874. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  18875. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18876. * The passed axis is also normalized.
  18877. * Returns the TransformNode.
  18878. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  18879. */
  18880. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  18881. axis.normalize();
  18882. if (!this.rotationQuaternion) {
  18883. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18884. this.rotation.copyFromFloats(0, 0, 0);
  18885. }
  18886. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  18887. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  18888. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  18889. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  18890. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  18891. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  18892. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  18893. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  18894. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18895. return this;
  18896. };
  18897. /**
  18898. * Translates the mesh along the axis vector for the passed distance in the given space.
  18899. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18900. * Returns the TransformNode.
  18901. */
  18902. TransformNode.prototype.translate = function (axis, distance, space) {
  18903. var displacementVector = axis.scale(distance);
  18904. if (!space || space === BABYLON.Space.LOCAL) {
  18905. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  18906. this.setPositionWithLocalVector(tempV3);
  18907. }
  18908. else {
  18909. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  18910. }
  18911. return this;
  18912. };
  18913. /**
  18914. * Adds a rotation step to the mesh current rotation.
  18915. * x, y, z are Euler angles expressed in radians.
  18916. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  18917. * This means this rotation is made in the mesh local space only.
  18918. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  18919. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  18920. * ```javascript
  18921. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  18922. * ```
  18923. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  18924. * 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.
  18925. * Returns the TransformNode.
  18926. */
  18927. TransformNode.prototype.addRotation = function (x, y, z) {
  18928. var rotationQuaternion;
  18929. if (this.rotationQuaternion) {
  18930. rotationQuaternion = this.rotationQuaternion;
  18931. }
  18932. else {
  18933. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  18934. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  18935. }
  18936. var accumulation = BABYLON.Tmp.Quaternion[0];
  18937. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  18938. rotationQuaternion.multiplyInPlace(accumulation);
  18939. if (!this.rotationQuaternion) {
  18940. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  18941. }
  18942. return this;
  18943. };
  18944. /**
  18945. * Computes the mesh World matrix and returns it.
  18946. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  18947. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  18948. * If the parameter `force`is set to `true`, the actual computation is done.
  18949. * Returns the mesh World Matrix.
  18950. */
  18951. TransformNode.prototype.computeWorldMatrix = function (force) {
  18952. if (this._isWorldMatrixFrozen) {
  18953. return this._worldMatrix;
  18954. }
  18955. if (!force && this.isSynchronized(true)) {
  18956. this._currentRenderId = this.getScene().getRenderId();
  18957. return this._worldMatrix;
  18958. }
  18959. this._cache.position.copyFrom(this.position);
  18960. this._cache.scaling.copyFrom(this.scaling);
  18961. this._cache.pivotMatrixUpdated = false;
  18962. this._cache.billboardMode = this.billboardMode;
  18963. this._currentRenderId = this.getScene().getRenderId();
  18964. this._childRenderId = this.getScene().getRenderId();
  18965. this._isDirty = false;
  18966. // Scaling
  18967. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  18968. // Rotation
  18969. //rotate, if quaternion is set and rotation was used
  18970. if (this.rotationQuaternion) {
  18971. var len = this.rotation.length();
  18972. if (len) {
  18973. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  18974. this.rotation.copyFromFloats(0, 0, 0);
  18975. }
  18976. }
  18977. if (this.rotationQuaternion) {
  18978. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  18979. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  18980. }
  18981. else {
  18982. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  18983. this._cache.rotation.copyFrom(this.rotation);
  18984. }
  18985. // Translation
  18986. var camera = this.getScene().activeCamera;
  18987. if (this.infiniteDistance && !this.parent && camera) {
  18988. var cameraWorldMatrix = camera.getWorldMatrix();
  18989. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  18990. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  18991. }
  18992. else {
  18993. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  18994. }
  18995. // Composing transformations
  18996. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  18997. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  18998. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  18999. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  19000. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  19001. // Need to decompose each rotation here
  19002. var currentPosition = BABYLON.Tmp.Vector3[3];
  19003. if (this.parent && this.parent.getWorldMatrix) {
  19004. if (this._transformToBoneReferal) {
  19005. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19006. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  19007. }
  19008. else {
  19009. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  19010. }
  19011. }
  19012. else {
  19013. currentPosition.copyFrom(this.position);
  19014. }
  19015. currentPosition.subtractInPlace(camera.globalPosition);
  19016. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19017. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19018. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19019. }
  19020. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19021. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19022. }
  19023. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19024. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19025. }
  19026. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19027. }
  19028. else {
  19029. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19030. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19031. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19032. }
  19033. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19034. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19035. }
  19036. // Local world
  19037. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19038. // Parent
  19039. if (this.parent && this.parent.getWorldMatrix) {
  19040. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19041. if (this._transformToBoneReferal) {
  19042. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19043. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19044. }
  19045. else {
  19046. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19047. }
  19048. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19049. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19050. this._worldMatrix.copyFrom(this._localWorld);
  19051. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19052. }
  19053. else {
  19054. if (this._transformToBoneReferal) {
  19055. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19056. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19057. }
  19058. else {
  19059. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19060. }
  19061. }
  19062. this._markSyncedWithParent();
  19063. }
  19064. else {
  19065. this._worldMatrix.copyFrom(this._localWorld);
  19066. }
  19067. // Post multiply inverse of pivotMatrix
  19068. if (this._postMultiplyPivotMatrix) {
  19069. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  19070. }
  19071. // Normal matrix
  19072. if (this.scaling.isNonUniform) {
  19073. this._updateNonUniformScalingState(true);
  19074. }
  19075. else if (this.parent && this.parent._nonUniformScaling) {
  19076. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19077. }
  19078. else {
  19079. this._updateNonUniformScalingState(false);
  19080. }
  19081. this._afterComputeWorldMatrix();
  19082. // Absolute position
  19083. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19084. // Callbacks
  19085. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19086. if (!this._poseMatrix) {
  19087. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19088. }
  19089. // Cache the determinant
  19090. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19091. return this._worldMatrix;
  19092. };
  19093. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19094. };
  19095. /**
  19096. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19097. * @param func: callback function to add
  19098. *
  19099. * Returns the TransformNode.
  19100. */
  19101. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19102. this.onAfterWorldMatrixUpdateObservable.add(func);
  19103. return this;
  19104. };
  19105. /**
  19106. * Removes a registered callback function.
  19107. * Returns the TransformNode.
  19108. */
  19109. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19110. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19111. return this;
  19112. };
  19113. /**
  19114. * Clone the current transform node
  19115. * Returns the new transform node
  19116. * @param name Name of the new clone
  19117. * @param newParent New parent for the clone
  19118. * @param doNotCloneChildren Do not clone children hierarchy
  19119. */
  19120. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19121. var _this = this;
  19122. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19123. result.name = name;
  19124. result.id = name;
  19125. if (newParent) {
  19126. result.parent = newParent;
  19127. }
  19128. if (!doNotCloneChildren) {
  19129. // Children
  19130. var directDescendants = this.getDescendants(true);
  19131. for (var index = 0; index < directDescendants.length; index++) {
  19132. var child = directDescendants[index];
  19133. if (child.clone) {
  19134. child.clone(name + "." + child.name, result);
  19135. }
  19136. }
  19137. }
  19138. return result;
  19139. };
  19140. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19141. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19142. serializationObject.type = this.getClassName();
  19143. // Parent
  19144. if (this.parent) {
  19145. serializationObject.parentId = this.parent.id;
  19146. }
  19147. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19148. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19149. }
  19150. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19151. serializationObject.isEnabled = this.isEnabled();
  19152. // Parent
  19153. if (this.parent) {
  19154. serializationObject.parentId = this.parent.id;
  19155. }
  19156. return serializationObject;
  19157. };
  19158. // Statics
  19159. /**
  19160. * Returns a new TransformNode object parsed from the source provided.
  19161. * The parameter `parsedMesh` is the source.
  19162. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19163. */
  19164. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19165. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19166. if (BABYLON.Tags) {
  19167. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19168. }
  19169. if (parsedTransformNode.localMatrix) {
  19170. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19171. }
  19172. else if (parsedTransformNode.pivotMatrix) {
  19173. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19174. }
  19175. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19176. // Parent
  19177. if (parsedTransformNode.parentId) {
  19178. transformNode._waitingParentId = parsedTransformNode.parentId;
  19179. }
  19180. return transformNode;
  19181. };
  19182. /**
  19183. * Releases resources associated with this transform node.
  19184. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19185. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19186. */
  19187. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19188. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19189. // Animations
  19190. this.getScene().stopAnimation(this);
  19191. // Remove from scene
  19192. this.getScene().removeTransformNode(this);
  19193. this.onAfterWorldMatrixUpdateObservable.clear();
  19194. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19195. };
  19196. // Statics
  19197. TransformNode.BILLBOARDMODE_NONE = 0;
  19198. TransformNode.BILLBOARDMODE_X = 1;
  19199. TransformNode.BILLBOARDMODE_Y = 2;
  19200. TransformNode.BILLBOARDMODE_Z = 4;
  19201. TransformNode.BILLBOARDMODE_ALL = 7;
  19202. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19203. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19204. __decorate([
  19205. BABYLON.serializeAsVector3()
  19206. ], TransformNode.prototype, "_rotation", void 0);
  19207. __decorate([
  19208. BABYLON.serializeAsQuaternion()
  19209. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19210. __decorate([
  19211. BABYLON.serializeAsVector3()
  19212. ], TransformNode.prototype, "_scaling", void 0);
  19213. __decorate([
  19214. BABYLON.serialize()
  19215. ], TransformNode.prototype, "billboardMode", void 0);
  19216. __decorate([
  19217. BABYLON.serialize()
  19218. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19219. __decorate([
  19220. BABYLON.serialize()
  19221. ], TransformNode.prototype, "infiniteDistance", void 0);
  19222. __decorate([
  19223. BABYLON.serializeAsVector3()
  19224. ], TransformNode.prototype, "position", void 0);
  19225. return TransformNode;
  19226. }(BABYLON.Node));
  19227. BABYLON.TransformNode = TransformNode;
  19228. })(BABYLON || (BABYLON = {}));
  19229. //# sourceMappingURL=babylon.transformNode.js.map
  19230. var BABYLON;
  19231. (function (BABYLON) {
  19232. /**
  19233. * Class used to store all common mesh properties
  19234. */
  19235. var AbstractMesh = /** @class */ (function (_super) {
  19236. __extends(AbstractMesh, _super);
  19237. // Constructor
  19238. /**
  19239. * Creates a new AbstractMesh
  19240. * @param name defines the name of the mesh
  19241. * @param scene defines the hosting scene
  19242. */
  19243. function AbstractMesh(name, scene) {
  19244. if (scene === void 0) { scene = null; }
  19245. var _this = _super.call(this, name, scene, false) || this;
  19246. _this._facetNb = 0; // facet number
  19247. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19248. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19249. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19250. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19251. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19252. _this._subDiv = {
  19253. max: 1,
  19254. X: 1,
  19255. Y: 1,
  19256. Z: 1
  19257. };
  19258. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19259. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19260. // Events
  19261. /**
  19262. * An event triggered when this mesh collides with another one
  19263. */
  19264. _this.onCollideObservable = new BABYLON.Observable();
  19265. /**
  19266. * An event triggered when the collision's position changes
  19267. */
  19268. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19269. /**
  19270. * An event triggered when material is changed
  19271. */
  19272. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19273. // Properties
  19274. /**
  19275. * Gets or sets the orientation for POV movement & rotation
  19276. */
  19277. _this.definedFacingForward = true;
  19278. /**
  19279. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19280. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19281. * * 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.
  19282. * @see http://doc.babylonjs.com/features/occlusionquery
  19283. */
  19284. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19285. /**
  19286. * 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:
  19287. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19288. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19289. * * 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.
  19290. * @see http://doc.babylonjs.com/features/occlusionquery
  19291. */
  19292. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19293. /**
  19294. * 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.
  19295. * The default value is -1 which means don't break the query and wait till the result
  19296. * @see http://doc.babylonjs.com/features/occlusionquery
  19297. */
  19298. _this.occlusionRetryCount = -1;
  19299. _this._occlusionInternalRetryCounter = 0;
  19300. _this._isOccluded = false;
  19301. _this._isOcclusionQueryInProgress = false;
  19302. _this._visibility = 1.0;
  19303. /** Gets or sets the alpha index used to sort transparent meshes
  19304. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19305. */
  19306. _this.alphaIndex = Number.MAX_VALUE;
  19307. /**
  19308. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19309. */
  19310. _this.isVisible = true;
  19311. /**
  19312. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19313. */
  19314. _this.isPickable = true;
  19315. /**
  19316. * Gets or sets a boolean indicating if the bounding box must be rendered as well (false by default)
  19317. */
  19318. _this.showBoundingBox = false;
  19319. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19320. _this.showSubMeshesBoundingBox = false;
  19321. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19322. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19323. */
  19324. _this.isBlocker = false;
  19325. /**
  19326. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19327. */
  19328. _this.enablePointerMoveEvents = false;
  19329. /**
  19330. * Specifies the rendering group id for this mesh (0 by default)
  19331. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19332. */
  19333. _this.renderingGroupId = 0;
  19334. _this._receiveShadows = false;
  19335. /**
  19336. * Gets or sets a boolean indicating if the outline must be rendered as well
  19337. * @see https://www.babylonjs-playground.com/#10WJ5S#3
  19338. */
  19339. _this.renderOutline = false;
  19340. /** Defines color to use when rendering outline */
  19341. _this.outlineColor = BABYLON.Color3.Red();
  19342. /** Define width to use when rendering outline */
  19343. _this.outlineWidth = 0.02;
  19344. /**
  19345. * Gets or sets a boolean indicating if the overlay must be rendered as well
  19346. * @see https://www.babylonjs-playground.com/#10WJ5S#2
  19347. */
  19348. _this.renderOverlay = false;
  19349. /** Defines color to use when rendering overlay */
  19350. _this.overlayColor = BABYLON.Color3.Red();
  19351. /** Defines alpha to use when rendering overlay */
  19352. _this.overlayAlpha = 0.5;
  19353. _this._hasVertexAlpha = false;
  19354. _this._useVertexColors = true;
  19355. _this._computeBonesUsingShaders = true;
  19356. _this._numBoneInfluencers = 4;
  19357. _this._applyFog = true;
  19358. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19359. _this.useOctreeForRenderingSelection = true;
  19360. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19361. _this.useOctreeForPicking = true;
  19362. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19363. _this.useOctreeForCollisions = true;
  19364. _this._layerMask = 0x0FFFFFFF;
  19365. /**
  19366. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19367. */
  19368. _this.alwaysSelectAsActiveMesh = false;
  19369. /**
  19370. * Gets or sets the current action manager
  19371. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19372. */
  19373. _this.actionManager = null;
  19374. /**
  19375. * Gets or sets impostor used for physic simulation
  19376. * @see http://doc.babylonjs.com/features/physics_engine
  19377. */
  19378. _this.physicsImpostor = null;
  19379. // Collisions
  19380. _this._checkCollisions = false;
  19381. _this._collisionMask = -1;
  19382. _this._collisionGroup = -1;
  19383. /**
  19384. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19385. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19386. */
  19387. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19388. /**
  19389. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19390. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19391. */
  19392. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19393. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19394. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19395. // Edges
  19396. /**
  19397. * Defines edge width used when edgesRenderer is enabled
  19398. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19399. */
  19400. _this.edgesWidth = 1;
  19401. /**
  19402. * Defines edge color used when edgesRenderer is enabled
  19403. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19404. */
  19405. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19406. // Cache
  19407. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19408. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19409. /** @hidden */
  19410. _this._renderId = 0;
  19411. /** @hidden */
  19412. _this._intersectionsInProgress = new Array();
  19413. /** @hidden */
  19414. _this._unIndexed = false;
  19415. /** @hidden */
  19416. _this._lightSources = new Array();
  19417. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19418. if (collidedMesh === void 0) { collidedMesh = null; }
  19419. //TODO move this to the collision coordinator!
  19420. if (_this.getScene().workerCollisions)
  19421. newPosition.multiplyInPlace(_this._collider._radius);
  19422. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19423. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19424. _this.position.addInPlace(_this._diffPositionForCollisions);
  19425. }
  19426. if (collidedMesh) {
  19427. _this.onCollideObservable.notifyObservers(collidedMesh);
  19428. }
  19429. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19430. };
  19431. _this.getScene().addMesh(_this);
  19432. _this._resyncLightSources();
  19433. return _this;
  19434. }
  19435. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19436. /**
  19437. * No billboard
  19438. */
  19439. get: function () {
  19440. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19441. },
  19442. enumerable: true,
  19443. configurable: true
  19444. });
  19445. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19446. /** Billboard on X axis */
  19447. get: function () {
  19448. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19449. },
  19450. enumerable: true,
  19451. configurable: true
  19452. });
  19453. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19454. /** Billboard on Y axis */
  19455. get: function () {
  19456. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19457. },
  19458. enumerable: true,
  19459. configurable: true
  19460. });
  19461. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19462. /** Billboard on Z axis */
  19463. get: function () {
  19464. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19465. },
  19466. enumerable: true,
  19467. configurable: true
  19468. });
  19469. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19470. /** Billboard on all axes */
  19471. get: function () {
  19472. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19473. },
  19474. enumerable: true,
  19475. configurable: true
  19476. });
  19477. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19478. /**
  19479. * Gets the number of facets in the mesh
  19480. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19481. */
  19482. get: function () {
  19483. return this._facetNb;
  19484. },
  19485. enumerable: true,
  19486. configurable: true
  19487. });
  19488. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19489. /**
  19490. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19491. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19492. */
  19493. get: function () {
  19494. return this._partitioningSubdivisions;
  19495. },
  19496. set: function (nb) {
  19497. this._partitioningSubdivisions = nb;
  19498. },
  19499. enumerable: true,
  19500. configurable: true
  19501. });
  19502. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19503. /**
  19504. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19505. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19506. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19507. */
  19508. get: function () {
  19509. return this._partitioningBBoxRatio;
  19510. },
  19511. set: function (ratio) {
  19512. this._partitioningBBoxRatio = ratio;
  19513. },
  19514. enumerable: true,
  19515. configurable: true
  19516. });
  19517. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19518. /**
  19519. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19520. * Works only for updatable meshes.
  19521. * Doesn't work with multi-materials
  19522. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19523. */
  19524. get: function () {
  19525. return this._facetDepthSort;
  19526. },
  19527. set: function (sort) {
  19528. this._facetDepthSort = sort;
  19529. },
  19530. enumerable: true,
  19531. configurable: true
  19532. });
  19533. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19534. /**
  19535. * The location (Vector3) where the facet depth sort must be computed from.
  19536. * By default, the active camera position.
  19537. * Used only when facet depth sort is enabled
  19538. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19539. */
  19540. get: function () {
  19541. return this._facetDepthSortFrom;
  19542. },
  19543. set: function (location) {
  19544. this._facetDepthSortFrom = location;
  19545. },
  19546. enumerable: true,
  19547. configurable: true
  19548. });
  19549. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19550. /**
  19551. * gets a boolean indicating if facetData is enabled
  19552. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19553. */
  19554. get: function () {
  19555. return this._facetDataEnabled;
  19556. },
  19557. enumerable: true,
  19558. configurable: true
  19559. });
  19560. /** @hidden */
  19561. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19562. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19563. return false;
  19564. }
  19565. this._markSubMeshesAsMiscDirty();
  19566. return true;
  19567. };
  19568. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19569. /** Set a function to call when this mesh collides with another one */
  19570. set: function (callback) {
  19571. if (this._onCollideObserver) {
  19572. this.onCollideObservable.remove(this._onCollideObserver);
  19573. }
  19574. this._onCollideObserver = this.onCollideObservable.add(callback);
  19575. },
  19576. enumerable: true,
  19577. configurable: true
  19578. });
  19579. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19580. /** Set a function to call when the collision's position changes */
  19581. set: function (callback) {
  19582. if (this._onCollisionPositionChangeObserver) {
  19583. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19584. }
  19585. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19586. },
  19587. enumerable: true,
  19588. configurable: true
  19589. });
  19590. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19591. /**
  19592. * 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
  19593. * @see http://doc.babylonjs.com/features/occlusionquery
  19594. */
  19595. get: function () {
  19596. return this._isOccluded;
  19597. },
  19598. set: function (value) {
  19599. this._isOccluded = value;
  19600. },
  19601. enumerable: true,
  19602. configurable: true
  19603. });
  19604. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19605. /**
  19606. * Flag to check the progress status of the query
  19607. * @see http://doc.babylonjs.com/features/occlusionquery
  19608. */
  19609. get: function () {
  19610. return this._isOcclusionQueryInProgress;
  19611. },
  19612. enumerable: true,
  19613. configurable: true
  19614. });
  19615. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19616. /**
  19617. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19618. */
  19619. get: function () {
  19620. return this._visibility;
  19621. },
  19622. /**
  19623. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19624. */
  19625. set: function (value) {
  19626. if (this._visibility === value) {
  19627. return;
  19628. }
  19629. this._visibility = value;
  19630. this._markSubMeshesAsMiscDirty();
  19631. },
  19632. enumerable: true,
  19633. configurable: true
  19634. });
  19635. Object.defineProperty(AbstractMesh.prototype, "material", {
  19636. /** Gets or sets current material */
  19637. get: function () {
  19638. return this._material;
  19639. },
  19640. set: function (value) {
  19641. if (this._material === value) {
  19642. return;
  19643. }
  19644. this._material = value;
  19645. if (this.onMaterialChangedObservable.hasObservers) {
  19646. this.onMaterialChangedObservable.notifyObservers(this);
  19647. }
  19648. if (!this.subMeshes) {
  19649. return;
  19650. }
  19651. this._unBindEffect();
  19652. },
  19653. enumerable: true,
  19654. configurable: true
  19655. });
  19656. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  19657. /**
  19658. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  19659. * @see http://doc.babylonjs.com/babylon101/shadows
  19660. */
  19661. get: function () {
  19662. return this._receiveShadows;
  19663. },
  19664. set: function (value) {
  19665. if (this._receiveShadows === value) {
  19666. return;
  19667. }
  19668. this._receiveShadows = value;
  19669. this._markSubMeshesAsLightDirty();
  19670. },
  19671. enumerable: true,
  19672. configurable: true
  19673. });
  19674. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  19675. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  19676. get: function () {
  19677. return this._hasVertexAlpha;
  19678. },
  19679. set: function (value) {
  19680. if (this._hasVertexAlpha === value) {
  19681. return;
  19682. }
  19683. this._hasVertexAlpha = value;
  19684. this._markSubMeshesAsAttributesDirty();
  19685. this._markSubMeshesAsMiscDirty();
  19686. },
  19687. enumerable: true,
  19688. configurable: true
  19689. });
  19690. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  19691. /** 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) */
  19692. get: function () {
  19693. return this._useVertexColors;
  19694. },
  19695. set: function (value) {
  19696. if (this._useVertexColors === value) {
  19697. return;
  19698. }
  19699. this._useVertexColors = value;
  19700. this._markSubMeshesAsAttributesDirty();
  19701. },
  19702. enumerable: true,
  19703. configurable: true
  19704. });
  19705. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  19706. /**
  19707. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  19708. */
  19709. get: function () {
  19710. return this._computeBonesUsingShaders;
  19711. },
  19712. set: function (value) {
  19713. if (this._computeBonesUsingShaders === value) {
  19714. return;
  19715. }
  19716. this._computeBonesUsingShaders = value;
  19717. this._markSubMeshesAsAttributesDirty();
  19718. },
  19719. enumerable: true,
  19720. configurable: true
  19721. });
  19722. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  19723. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  19724. get: function () {
  19725. return this._numBoneInfluencers;
  19726. },
  19727. set: function (value) {
  19728. if (this._numBoneInfluencers === value) {
  19729. return;
  19730. }
  19731. this._numBoneInfluencers = value;
  19732. this._markSubMeshesAsAttributesDirty();
  19733. },
  19734. enumerable: true,
  19735. configurable: true
  19736. });
  19737. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  19738. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  19739. get: function () {
  19740. return this._applyFog;
  19741. },
  19742. set: function (value) {
  19743. if (this._applyFog === value) {
  19744. return;
  19745. }
  19746. this._applyFog = value;
  19747. this._markSubMeshesAsMiscDirty();
  19748. },
  19749. enumerable: true,
  19750. configurable: true
  19751. });
  19752. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  19753. /**
  19754. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  19755. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  19756. */
  19757. get: function () {
  19758. return this._layerMask;
  19759. },
  19760. set: function (value) {
  19761. if (value === this._layerMask) {
  19762. return;
  19763. }
  19764. this._layerMask = value;
  19765. this._resyncLightSources();
  19766. },
  19767. enumerable: true,
  19768. configurable: true
  19769. });
  19770. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  19771. /**
  19772. * Gets or sets a collision mask used to mask collisions (default is -1).
  19773. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19774. */
  19775. get: function () {
  19776. return this._collisionMask;
  19777. },
  19778. set: function (mask) {
  19779. this._collisionMask = !isNaN(mask) ? mask : -1;
  19780. },
  19781. enumerable: true,
  19782. configurable: true
  19783. });
  19784. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  19785. /**
  19786. * Gets or sets the current collision group mask (-1 by default).
  19787. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19788. */
  19789. get: function () {
  19790. return this._collisionGroup;
  19791. },
  19792. set: function (mask) {
  19793. this._collisionGroup = !isNaN(mask) ? mask : -1;
  19794. },
  19795. enumerable: true,
  19796. configurable: true
  19797. });
  19798. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  19799. /** @hidden */
  19800. get: function () {
  19801. return null;
  19802. },
  19803. enumerable: true,
  19804. configurable: true
  19805. });
  19806. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  19807. get: function () {
  19808. return this._skeleton;
  19809. },
  19810. /**
  19811. * Gets or sets a skeleton to apply skining transformations
  19812. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  19813. */
  19814. set: function (value) {
  19815. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  19816. this._skeleton._unregisterMeshWithPoseMatrix(this);
  19817. }
  19818. if (value && value.needInitialSkinMatrix) {
  19819. value._registerMeshWithPoseMatrix(this);
  19820. }
  19821. this._skeleton = value;
  19822. if (!this._skeleton) {
  19823. this._bonesTransformMatrices = null;
  19824. }
  19825. this._markSubMeshesAsAttributesDirty();
  19826. },
  19827. enumerable: true,
  19828. configurable: true
  19829. });
  19830. /**
  19831. * Returns the string "AbstractMesh"
  19832. * @returns "AbstractMesh"
  19833. */
  19834. AbstractMesh.prototype.getClassName = function () {
  19835. return "AbstractMesh";
  19836. };
  19837. /**
  19838. * Gets a string representation of the current mesh
  19839. * @param fullDetails defines a boolean indicating if full details must be included
  19840. * @returns a string representation of the current mesh
  19841. */
  19842. AbstractMesh.prototype.toString = function (fullDetails) {
  19843. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  19844. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  19845. if (this._skeleton) {
  19846. ret += ", skeleton: " + this._skeleton.name;
  19847. }
  19848. if (fullDetails) {
  19849. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  19850. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  19851. }
  19852. return ret;
  19853. };
  19854. /** @hidden */
  19855. AbstractMesh.prototype._rebuild = function () {
  19856. if (this._occlusionQuery) {
  19857. this._occlusionQuery = null;
  19858. }
  19859. if (this._edgesRenderer) {
  19860. this._edgesRenderer._rebuild();
  19861. }
  19862. if (!this.subMeshes) {
  19863. return;
  19864. }
  19865. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19866. var subMesh = _a[_i];
  19867. subMesh._rebuild();
  19868. }
  19869. };
  19870. /** @hidden */
  19871. AbstractMesh.prototype._resyncLightSources = function () {
  19872. this._lightSources.length = 0;
  19873. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  19874. var light = _a[_i];
  19875. if (!light.isEnabled()) {
  19876. continue;
  19877. }
  19878. if (light.canAffectMesh(this)) {
  19879. this._lightSources.push(light);
  19880. }
  19881. }
  19882. this._markSubMeshesAsLightDirty();
  19883. };
  19884. /** @hidden */
  19885. AbstractMesh.prototype._resyncLighSource = function (light) {
  19886. var isIn = light.isEnabled() && light.canAffectMesh(this);
  19887. var index = this._lightSources.indexOf(light);
  19888. if (index === -1) {
  19889. if (!isIn) {
  19890. return;
  19891. }
  19892. this._lightSources.push(light);
  19893. }
  19894. else {
  19895. if (isIn) {
  19896. return;
  19897. }
  19898. this._lightSources.splice(index, 1);
  19899. }
  19900. this._markSubMeshesAsLightDirty();
  19901. };
  19902. /** @hidden */
  19903. AbstractMesh.prototype._unBindEffect = function () {
  19904. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19905. var subMesh = _a[_i];
  19906. subMesh.setEffect(null);
  19907. }
  19908. };
  19909. /** @hidden */
  19910. AbstractMesh.prototype._removeLightSource = function (light) {
  19911. var index = this._lightSources.indexOf(light);
  19912. if (index === -1) {
  19913. return;
  19914. }
  19915. this._lightSources.splice(index, 1);
  19916. this._markSubMeshesAsLightDirty();
  19917. };
  19918. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  19919. if (!this.subMeshes) {
  19920. return;
  19921. }
  19922. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19923. var subMesh = _a[_i];
  19924. if (subMesh._materialDefines) {
  19925. func(subMesh._materialDefines);
  19926. }
  19927. }
  19928. };
  19929. /** @hidden */
  19930. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  19931. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  19932. };
  19933. /** @hidden */
  19934. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  19935. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  19936. };
  19937. /** @hidden */
  19938. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  19939. if (!this.subMeshes) {
  19940. return;
  19941. }
  19942. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19943. var subMesh = _a[_i];
  19944. var material = subMesh.getMaterial();
  19945. if (material) {
  19946. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  19947. }
  19948. }
  19949. };
  19950. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  19951. /**
  19952. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  19953. */
  19954. get: function () {
  19955. return this._scaling;
  19956. },
  19957. set: function (newScaling) {
  19958. this._scaling = newScaling;
  19959. if (this.physicsImpostor) {
  19960. this.physicsImpostor.forceUpdate();
  19961. }
  19962. },
  19963. enumerable: true,
  19964. configurable: true
  19965. });
  19966. // Methods
  19967. /**
  19968. * Disables the mesh edge rendering mode
  19969. * @returns the currentAbstractMesh
  19970. */
  19971. AbstractMesh.prototype.disableEdgesRendering = function () {
  19972. if (this._edgesRenderer) {
  19973. this._edgesRenderer.dispose();
  19974. this._edgesRenderer = null;
  19975. }
  19976. return this;
  19977. };
  19978. /**
  19979. * Enables the edge rendering mode on the mesh.
  19980. * This mode makes the mesh edges visible
  19981. * @param epsilon defines the maximal distance between two angles to detect a face
  19982. * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces
  19983. * @returns the currentAbstractMesh
  19984. * @see https://www.babylonjs-playground.com/#19O9TU#0
  19985. */
  19986. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  19987. if (epsilon === void 0) { epsilon = 0.95; }
  19988. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  19989. this.disableEdgesRendering();
  19990. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  19991. return this;
  19992. };
  19993. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  19994. /**
  19995. * Returns true if the mesh is blocked. Implemented by child classes
  19996. */
  19997. get: function () {
  19998. return false;
  19999. },
  20000. enumerable: true,
  20001. configurable: true
  20002. });
  20003. /**
  20004. * Returns the mesh itself by default. Implemented by child classes
  20005. * @param camera defines the camera to use to pick the right LOD level
  20006. * @returns the currentAbstractMesh
  20007. */
  20008. AbstractMesh.prototype.getLOD = function (camera) {
  20009. return this;
  20010. };
  20011. /**
  20012. * Returns 0 by default. Implemented by child classes
  20013. * @returns an integer
  20014. */
  20015. AbstractMesh.prototype.getTotalVertices = function () {
  20016. return 0;
  20017. };
  20018. /**
  20019. * Returns null by default. Implemented by child classes
  20020. * @returns null
  20021. */
  20022. AbstractMesh.prototype.getIndices = function () {
  20023. return null;
  20024. };
  20025. /**
  20026. * Returns the array of the requested vertex data kind. Implemented by child classes
  20027. * @param kind defines the vertex data kind to use
  20028. * @returns null
  20029. */
  20030. AbstractMesh.prototype.getVerticesData = function (kind) {
  20031. return null;
  20032. };
  20033. /**
  20034. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20035. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20036. * Note that a new underlying VertexBuffer object is created each call.
  20037. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20038. * @param kind defines vertex data kind:
  20039. * * BABYLON.VertexBuffer.PositionKind
  20040. * * BABYLON.VertexBuffer.UVKind
  20041. * * BABYLON.VertexBuffer.UV2Kind
  20042. * * BABYLON.VertexBuffer.UV3Kind
  20043. * * BABYLON.VertexBuffer.UV4Kind
  20044. * * BABYLON.VertexBuffer.UV5Kind
  20045. * * BABYLON.VertexBuffer.UV6Kind
  20046. * * BABYLON.VertexBuffer.ColorKind
  20047. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20048. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20049. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20050. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20051. * @param data defines the data source
  20052. * @param updatable defines if the data must be flagged as updatable (or static)
  20053. * @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
  20054. * @returns the current mesh
  20055. */
  20056. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20057. return this;
  20058. };
  20059. /**
  20060. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20061. * If the mesh has no geometry, it is simply returned as it is.
  20062. * @param kind defines vertex data kind:
  20063. * * BABYLON.VertexBuffer.PositionKind
  20064. * * BABYLON.VertexBuffer.UVKind
  20065. * * BABYLON.VertexBuffer.UV2Kind
  20066. * * BABYLON.VertexBuffer.UV3Kind
  20067. * * BABYLON.VertexBuffer.UV4Kind
  20068. * * BABYLON.VertexBuffer.UV5Kind
  20069. * * BABYLON.VertexBuffer.UV6Kind
  20070. * * BABYLON.VertexBuffer.ColorKind
  20071. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20072. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20073. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20074. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20075. * @param data defines the data source
  20076. * @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
  20077. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20078. * @returns the current mesh
  20079. */
  20080. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20081. return this;
  20082. };
  20083. /**
  20084. * Sets the mesh indices,
  20085. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20086. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20087. * @param totalVertices Defines the total number of vertices
  20088. * @returns the current mesh
  20089. */
  20090. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20091. return this;
  20092. };
  20093. /**
  20094. * Gets a boolean indicating if specific vertex data is present
  20095. * @param kind defines the vertex data kind to use
  20096. * @returns true is data kind is present
  20097. */
  20098. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20099. return false;
  20100. };
  20101. /**
  20102. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20103. * @returns a BoundingInfo
  20104. */
  20105. AbstractMesh.prototype.getBoundingInfo = function () {
  20106. if (this._masterMesh) {
  20107. return this._masterMesh.getBoundingInfo();
  20108. }
  20109. if (!this._boundingInfo) {
  20110. // this._boundingInfo is being created here
  20111. this._updateBoundingInfo();
  20112. }
  20113. // cannot be null.
  20114. return this._boundingInfo;
  20115. };
  20116. /**
  20117. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20118. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20119. * @returns the current mesh
  20120. */
  20121. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20122. if (includeDescendants === void 0) { includeDescendants = true; }
  20123. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20124. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20125. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20126. if (maxDimension === 0) {
  20127. return this;
  20128. }
  20129. var scale = 1 / maxDimension;
  20130. this.scaling.scaleInPlace(scale);
  20131. return this;
  20132. };
  20133. /**
  20134. * Overwrite the current bounding info
  20135. * @param boundingInfo defines the new bounding info
  20136. * @returns the current mesh
  20137. */
  20138. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20139. this._boundingInfo = boundingInfo;
  20140. return this;
  20141. };
  20142. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20143. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20144. get: function () {
  20145. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20146. },
  20147. enumerable: true,
  20148. configurable: true
  20149. });
  20150. /** @hidden */
  20151. AbstractMesh.prototype._preActivate = function () {
  20152. };
  20153. /** @hidden */
  20154. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20155. };
  20156. /** @hidden */
  20157. AbstractMesh.prototype._activate = function (renderId) {
  20158. this._renderId = renderId;
  20159. };
  20160. /**
  20161. * Gets the current world matrix
  20162. * @returns a Matrix
  20163. */
  20164. AbstractMesh.prototype.getWorldMatrix = function () {
  20165. if (this._masterMesh) {
  20166. return this._masterMesh.getWorldMatrix();
  20167. }
  20168. return _super.prototype.getWorldMatrix.call(this);
  20169. };
  20170. /** @hidden */
  20171. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20172. if (this._masterMesh) {
  20173. return this._masterMesh._getWorldMatrixDeterminant();
  20174. }
  20175. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20176. };
  20177. // ================================== Point of View Movement =================================
  20178. /**
  20179. * Perform relative position change from the point of view of behind the front of the mesh.
  20180. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20181. * Supports definition of mesh facing forward or backward
  20182. * @param amountRight defines the distance on the right axis
  20183. * @param amountUp defines the distance on the up axis
  20184. * @param amountForward defines the distance on the forward axis
  20185. * @returns the current mesh
  20186. */
  20187. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20188. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20189. return this;
  20190. };
  20191. /**
  20192. * Calculate relative position change from the point of view of behind the front of the mesh.
  20193. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20194. * Supports definition of mesh facing forward or backward
  20195. * @param amountRight defines the distance on the right axis
  20196. * @param amountUp defines the distance on the up axis
  20197. * @param amountForward defines the distance on the forward axis
  20198. * @returns the new displacement vector
  20199. */
  20200. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20201. var rotMatrix = new BABYLON.Matrix();
  20202. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20203. rotQuaternion.toRotationMatrix(rotMatrix);
  20204. var translationDelta = BABYLON.Vector3.Zero();
  20205. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20206. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20207. return translationDelta;
  20208. };
  20209. // ================================== Point of View Rotation =================================
  20210. /**
  20211. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20212. * Supports definition of mesh facing forward or backward
  20213. * @param flipBack defines the flip
  20214. * @param twirlClockwise defines the twirl
  20215. * @param tiltRight defines the tilt
  20216. * @returns the current mesh
  20217. */
  20218. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20219. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20220. return this;
  20221. };
  20222. /**
  20223. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20224. * Supports definition of mesh facing forward or backward.
  20225. * @param flipBack defines the flip
  20226. * @param twirlClockwise defines the twirl
  20227. * @param tiltRight defines the tilt
  20228. * @returns the new rotation vector
  20229. */
  20230. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20231. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20232. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20233. };
  20234. /**
  20235. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20236. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20237. * @returns the new bounding vectors
  20238. */
  20239. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  20240. if (includeDescendants === void 0) { includeDescendants = true; }
  20241. // Ensures that all world matrix will be recomputed.
  20242. this.getScene().incrementRenderId();
  20243. this.computeWorldMatrix(true);
  20244. var min;
  20245. var max;
  20246. var boundingInfo = this.getBoundingInfo();
  20247. if (!this.subMeshes) {
  20248. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20249. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20250. }
  20251. else {
  20252. min = boundingInfo.boundingBox.minimumWorld;
  20253. max = boundingInfo.boundingBox.maximumWorld;
  20254. }
  20255. if (includeDescendants) {
  20256. var descendants = this.getDescendants(false);
  20257. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20258. var descendant = descendants_1[_i];
  20259. var childMesh = descendant;
  20260. childMesh.computeWorldMatrix(true);
  20261. //make sure we have the needed params to get mix and max
  20262. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20263. continue;
  20264. }
  20265. var childBoundingInfo = childMesh.getBoundingInfo();
  20266. var boundingBox = childBoundingInfo.boundingBox;
  20267. var minBox = boundingBox.minimumWorld;
  20268. var maxBox = boundingBox.maximumWorld;
  20269. BABYLON.Tools.CheckExtends(minBox, min, max);
  20270. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20271. }
  20272. }
  20273. return {
  20274. min: min,
  20275. max: max
  20276. };
  20277. };
  20278. /** @hidden */
  20279. AbstractMesh.prototype._updateBoundingInfo = function () {
  20280. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20281. this._boundingInfo.update(this.worldMatrixFromCache);
  20282. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20283. return this;
  20284. };
  20285. /** @hidden */
  20286. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20287. if (!this.subMeshes) {
  20288. return this;
  20289. }
  20290. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20291. var subMesh = this.subMeshes[subIndex];
  20292. if (!subMesh.IsGlobal) {
  20293. subMesh.updateBoundingInfo(matrix);
  20294. }
  20295. }
  20296. return this;
  20297. };
  20298. /** @hidden */
  20299. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20300. // Bounding info
  20301. this._updateBoundingInfo();
  20302. };
  20303. /**
  20304. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20305. * A mesh is in the frustum if its bounding box intersects the frustum
  20306. * @param frustumPlanes defines the frustum to test
  20307. * @returns true if the mesh is in the frustum planes
  20308. */
  20309. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20310. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  20311. };
  20312. /**
  20313. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20314. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20315. * @param frustumPlanes defines the frustum to test
  20316. * @returns true if the mesh is completely in the frustum planes
  20317. */
  20318. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20319. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20320. };
  20321. /**
  20322. * True if the mesh intersects another mesh or a SolidParticle object
  20323. * @param mesh defines a target mesh or SolidParticle to test
  20324. * @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)
  20325. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20326. * @returns true if there is an intersection
  20327. */
  20328. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20329. if (precise === void 0) { precise = false; }
  20330. if (!this._boundingInfo || !mesh._boundingInfo) {
  20331. return false;
  20332. }
  20333. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20334. return true;
  20335. }
  20336. if (includeDescendants) {
  20337. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20338. var child = _a[_i];
  20339. if (child.intersectsMesh(mesh, precise, true)) {
  20340. return true;
  20341. }
  20342. }
  20343. }
  20344. return false;
  20345. };
  20346. /**
  20347. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20348. * @param point defines the point to test
  20349. * @returns true if there is an intersection
  20350. */
  20351. AbstractMesh.prototype.intersectsPoint = function (point) {
  20352. if (!this._boundingInfo) {
  20353. return false;
  20354. }
  20355. return this._boundingInfo.intersectsPoint(point);
  20356. };
  20357. /**
  20358. * Gets the current physics impostor
  20359. * @see http://doc.babylonjs.com/features/physics_engine
  20360. * @returns a physics impostor or null
  20361. */
  20362. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20363. return this.physicsImpostor;
  20364. };
  20365. /**
  20366. * Gets the position of the current mesh in camera space
  20367. * @param camera defines the camera to use
  20368. * @returns a position
  20369. */
  20370. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20371. if (camera === void 0) { camera = null; }
  20372. if (!camera) {
  20373. camera = this.getScene().activeCamera;
  20374. }
  20375. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20376. };
  20377. /**
  20378. * Returns the distance from the mesh to the active camera
  20379. * @param camera defines the camera to use
  20380. * @returns the distance
  20381. */
  20382. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20383. if (camera === void 0) { camera = null; }
  20384. if (!camera) {
  20385. camera = this.getScene().activeCamera;
  20386. }
  20387. return this.absolutePosition.subtract(camera.position).length();
  20388. };
  20389. /**
  20390. * Apply a physic impulse to the mesh
  20391. * @param force defines the force to apply
  20392. * @param contactPoint defines where to apply the force
  20393. * @returns the current mesh
  20394. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  20395. */
  20396. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20397. if (!this.physicsImpostor) {
  20398. return this;
  20399. }
  20400. this.physicsImpostor.applyImpulse(force, contactPoint);
  20401. return this;
  20402. };
  20403. /**
  20404. * Creates a physic joint between two meshes
  20405. * @param otherMesh defines the other mesh to use
  20406. * @param pivot1 defines the pivot to use on this mesh
  20407. * @param pivot2 defines the pivot to use on the other mesh
  20408. * @param options defines additional options (can be plugin dependent)
  20409. * @returns the current mesh
  20410. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  20411. */
  20412. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20413. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20414. return this;
  20415. }
  20416. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20417. mainPivot: pivot1,
  20418. connectedPivot: pivot2,
  20419. nativeParams: options
  20420. });
  20421. return this;
  20422. };
  20423. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20424. // Collisions
  20425. /**
  20426. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20427. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20428. */
  20429. get: function () {
  20430. return this._checkCollisions;
  20431. },
  20432. set: function (collisionEnabled) {
  20433. this._checkCollisions = collisionEnabled;
  20434. if (this.getScene().workerCollisions) {
  20435. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20436. }
  20437. },
  20438. enumerable: true,
  20439. configurable: true
  20440. });
  20441. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20442. /**
  20443. * Gets Collider object used to compute collisions (not physics)
  20444. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20445. */
  20446. get: function () {
  20447. return this._collider;
  20448. },
  20449. enumerable: true,
  20450. configurable: true
  20451. });
  20452. /**
  20453. * Move the mesh using collision engine
  20454. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20455. * @param displacement defines the requested displacement vector
  20456. * @returns the current mesh
  20457. */
  20458. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20459. var globalPosition = this.getAbsolutePosition();
  20460. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20461. if (!this._collider) {
  20462. this._collider = new BABYLON.Collider();
  20463. }
  20464. this._collider._radius = this.ellipsoid;
  20465. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20466. return this;
  20467. };
  20468. // Submeshes octree
  20469. /**
  20470. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  20471. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  20472. * @param maxCapacity defines the maximum size of each block (64 by default)
  20473. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  20474. * @returns the new octree
  20475. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  20476. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  20477. */
  20478. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  20479. if (maxCapacity === void 0) { maxCapacity = 64; }
  20480. if (maxDepth === void 0) { maxDepth = 2; }
  20481. if (!this._submeshesOctree) {
  20482. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  20483. }
  20484. this.computeWorldMatrix(true);
  20485. var boundingInfo = this.getBoundingInfo();
  20486. // Update octree
  20487. var bbox = boundingInfo.boundingBox;
  20488. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  20489. return this._submeshesOctree;
  20490. };
  20491. // Collisions
  20492. /** @hidden */
  20493. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20494. this._generatePointsArray();
  20495. if (!this._positions) {
  20496. return this;
  20497. }
  20498. // Transformation
  20499. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20500. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20501. subMesh._lastColliderWorldVertices = [];
  20502. subMesh._trianglePlanes = [];
  20503. var start = subMesh.verticesStart;
  20504. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20505. for (var i = start; i < end; i++) {
  20506. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20507. }
  20508. }
  20509. // Collide
  20510. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20511. if (collider.collisionFound) {
  20512. collider.collidedMesh = this;
  20513. }
  20514. return this;
  20515. };
  20516. /** @hidden */
  20517. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20518. var subMeshes;
  20519. var len;
  20520. // Octrees
  20521. if (this._submeshesOctree && this.useOctreeForCollisions) {
  20522. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  20523. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  20524. len = intersections.length;
  20525. subMeshes = intersections.data;
  20526. }
  20527. else {
  20528. subMeshes = this.subMeshes;
  20529. len = subMeshes.length;
  20530. }
  20531. for (var index = 0; index < len; index++) {
  20532. var subMesh = subMeshes[index];
  20533. // Bounding test
  20534. if (len > 1 && !subMesh._checkCollision(collider))
  20535. continue;
  20536. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20537. }
  20538. return this;
  20539. };
  20540. /** @hidden */
  20541. AbstractMesh.prototype._checkCollision = function (collider) {
  20542. // Bounding box test
  20543. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20544. return this;
  20545. // Transformation matrix
  20546. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20547. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20548. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20549. return this;
  20550. };
  20551. // Picking
  20552. /** @hidden */
  20553. AbstractMesh.prototype._generatePointsArray = function () {
  20554. return false;
  20555. };
  20556. /**
  20557. * Checks if the passed Ray intersects with the mesh
  20558. * @param ray defines the ray to use
  20559. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20560. * @returns the picking info
  20561. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20562. */
  20563. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20564. var pickingInfo = new BABYLON.PickingInfo();
  20565. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20566. return pickingInfo;
  20567. }
  20568. if (!this._generatePointsArray()) {
  20569. return pickingInfo;
  20570. }
  20571. var intersectInfo = null;
  20572. // Octrees
  20573. var subMeshes;
  20574. var len;
  20575. if (this._submeshesOctree && this.useOctreeForPicking) {
  20576. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  20577. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  20578. len = intersections.length;
  20579. subMeshes = intersections.data;
  20580. }
  20581. else {
  20582. subMeshes = this.subMeshes;
  20583. len = subMeshes.length;
  20584. }
  20585. for (var index = 0; index < len; index++) {
  20586. var subMesh = subMeshes[index];
  20587. // Bounding test
  20588. if (len > 1 && !subMesh.canIntersects(ray))
  20589. continue;
  20590. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20591. if (currentIntersectInfo) {
  20592. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20593. intersectInfo = currentIntersectInfo;
  20594. intersectInfo.subMeshId = index;
  20595. if (fastCheck) {
  20596. break;
  20597. }
  20598. }
  20599. }
  20600. }
  20601. if (intersectInfo) {
  20602. // Get picked point
  20603. var world = this.getWorldMatrix();
  20604. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20605. var direction = ray.direction.clone();
  20606. direction = direction.scale(intersectInfo.distance);
  20607. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20608. var pickedPoint = worldOrigin.add(worldDirection);
  20609. // Return result
  20610. pickingInfo.hit = true;
  20611. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20612. pickingInfo.pickedPoint = pickedPoint;
  20613. pickingInfo.pickedMesh = this;
  20614. pickingInfo.bu = intersectInfo.bu || 0;
  20615. pickingInfo.bv = intersectInfo.bv || 0;
  20616. pickingInfo.faceId = intersectInfo.faceId;
  20617. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20618. return pickingInfo;
  20619. }
  20620. return pickingInfo;
  20621. };
  20622. /**
  20623. * Clones the current mesh
  20624. * @param name defines the mesh name
  20625. * @param newParent defines the new mesh parent
  20626. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  20627. * @returns the new mesh
  20628. */
  20629. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20630. return null;
  20631. };
  20632. /**
  20633. * Disposes all the submeshes of the current meshnp
  20634. * @returns the current mesh
  20635. */
  20636. AbstractMesh.prototype.releaseSubMeshes = function () {
  20637. if (this.subMeshes) {
  20638. while (this.subMeshes.length) {
  20639. this.subMeshes[0].dispose();
  20640. }
  20641. }
  20642. else {
  20643. this.subMeshes = new Array();
  20644. }
  20645. return this;
  20646. };
  20647. /**
  20648. * Releases resources associated with this abstract mesh.
  20649. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20650. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20651. */
  20652. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20653. var _this = this;
  20654. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20655. var index;
  20656. // Smart Array Retainers.
  20657. this.getScene().freeActiveMeshes();
  20658. this.getScene().freeRenderingGroups();
  20659. // Action manager
  20660. if (this.actionManager !== undefined && this.actionManager !== null) {
  20661. this.actionManager.dispose();
  20662. this.actionManager = null;
  20663. }
  20664. // Skeleton
  20665. this._skeleton = null;
  20666. // Physics
  20667. if (this.physicsImpostor) {
  20668. this.physicsImpostor.dispose( /*!doNotRecurse*/);
  20669. }
  20670. // Intersections in progress
  20671. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20672. var other = this._intersectionsInProgress[index];
  20673. var pos = other._intersectionsInProgress.indexOf(this);
  20674. other._intersectionsInProgress.splice(pos, 1);
  20675. }
  20676. this._intersectionsInProgress = [];
  20677. // Lights
  20678. var lights = this.getScene().lights;
  20679. lights.forEach(function (light) {
  20680. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  20681. if (meshIndex !== -1) {
  20682. light.includedOnlyMeshes.splice(meshIndex, 1);
  20683. }
  20684. meshIndex = light.excludedMeshes.indexOf(_this);
  20685. if (meshIndex !== -1) {
  20686. light.excludedMeshes.splice(meshIndex, 1);
  20687. }
  20688. // Shadow generators
  20689. var generator = light.getShadowGenerator();
  20690. if (generator) {
  20691. var shadowMap = generator.getShadowMap();
  20692. if (shadowMap && shadowMap.renderList) {
  20693. meshIndex = shadowMap.renderList.indexOf(_this);
  20694. if (meshIndex !== -1) {
  20695. shadowMap.renderList.splice(meshIndex, 1);
  20696. }
  20697. }
  20698. }
  20699. });
  20700. // Edges
  20701. if (this._edgesRenderer) {
  20702. this._edgesRenderer.dispose();
  20703. this._edgesRenderer = null;
  20704. }
  20705. // SubMeshes
  20706. if (this.getClassName() !== "InstancedMesh") {
  20707. this.releaseSubMeshes();
  20708. }
  20709. // Octree
  20710. var sceneOctree = this.getScene().selectionOctree;
  20711. if (sceneOctree !== undefined && sceneOctree !== null) {
  20712. var index = sceneOctree.dynamicContent.indexOf(this);
  20713. if (index !== -1) {
  20714. sceneOctree.dynamicContent.splice(index, 1);
  20715. }
  20716. }
  20717. // Query
  20718. var engine = this.getScene().getEngine();
  20719. if (this._occlusionQuery) {
  20720. this._isOcclusionQueryInProgress = false;
  20721. engine.deleteQuery(this._occlusionQuery);
  20722. this._occlusionQuery = null;
  20723. }
  20724. // Engine
  20725. engine.wipeCaches();
  20726. // Remove from scene
  20727. this.getScene().removeMesh(this);
  20728. if (disposeMaterialAndTextures) {
  20729. if (this.material) {
  20730. this.material.dispose(false, true);
  20731. }
  20732. }
  20733. if (!doNotRecurse) {
  20734. // Particles
  20735. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  20736. if (this.getScene().particleSystems[index].emitter === this) {
  20737. this.getScene().particleSystems[index].dispose();
  20738. index--;
  20739. }
  20740. }
  20741. }
  20742. // facet data
  20743. if (this._facetDataEnabled) {
  20744. this.disableFacetData();
  20745. }
  20746. this.onAfterWorldMatrixUpdateObservable.clear();
  20747. this.onCollideObservable.clear();
  20748. this.onCollisionPositionChangeObservable.clear();
  20749. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20750. };
  20751. /**
  20752. * Adds the passed mesh as a child to the current mesh
  20753. * @param mesh defines the child mesh
  20754. * @returns the current mesh
  20755. */
  20756. AbstractMesh.prototype.addChild = function (mesh) {
  20757. mesh.setParent(this);
  20758. return this;
  20759. };
  20760. /**
  20761. * Removes the passed mesh from the current mesh children list
  20762. * @param mesh defines the child mesh
  20763. * @returns the current mesh
  20764. */
  20765. AbstractMesh.prototype.removeChild = function (mesh) {
  20766. mesh.setParent(null);
  20767. return this;
  20768. };
  20769. // Facet data
  20770. /** @hidden */
  20771. AbstractMesh.prototype._initFacetData = function () {
  20772. if (!this._facetNormals) {
  20773. this._facetNormals = new Array();
  20774. }
  20775. if (!this._facetPositions) {
  20776. this._facetPositions = new Array();
  20777. }
  20778. if (!this._facetPartitioning) {
  20779. this._facetPartitioning = new Array();
  20780. }
  20781. this._facetNb = (this.getIndices().length / 3) | 0;
  20782. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  20783. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  20784. for (var f = 0; f < this._facetNb; f++) {
  20785. this._facetNormals[f] = BABYLON.Vector3.Zero();
  20786. this._facetPositions[f] = BABYLON.Vector3.Zero();
  20787. }
  20788. this._facetDataEnabled = true;
  20789. return this;
  20790. };
  20791. /**
  20792. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  20793. * This method can be called within the render loop.
  20794. * 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
  20795. * @returns the current mesh
  20796. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20797. */
  20798. AbstractMesh.prototype.updateFacetData = function () {
  20799. if (!this._facetDataEnabled) {
  20800. this._initFacetData();
  20801. }
  20802. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20803. var indices = this.getIndices();
  20804. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20805. var bInfo = this.getBoundingInfo();
  20806. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  20807. // init arrays, matrix and sort function on first call
  20808. this._facetDepthSortEnabled = true;
  20809. if (indices instanceof Uint16Array) {
  20810. this._depthSortedIndices = new Uint16Array(indices);
  20811. }
  20812. else if (indices instanceof Uint32Array) {
  20813. this._depthSortedIndices = new Uint32Array(indices);
  20814. }
  20815. else {
  20816. var needs32bits = false;
  20817. for (var i = 0; i < indices.length; i++) {
  20818. if (indices[i] > 65535) {
  20819. needs32bits = true;
  20820. break;
  20821. }
  20822. }
  20823. if (needs32bits) {
  20824. this._depthSortedIndices = new Uint32Array(indices);
  20825. }
  20826. else {
  20827. this._depthSortedIndices = new Uint16Array(indices);
  20828. }
  20829. }
  20830. this._facetDepthSortFunction = function (f1, f2) {
  20831. return (f2.sqDistance - f1.sqDistance);
  20832. };
  20833. if (!this._facetDepthSortFrom) {
  20834. var camera = this.getScene().activeCamera;
  20835. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  20836. }
  20837. this._depthSortedFacets = [];
  20838. for (var f = 0; f < this._facetNb; f++) {
  20839. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  20840. this._depthSortedFacets.push(depthSortedFacet);
  20841. }
  20842. this._invertedMatrix = BABYLON.Matrix.Identity();
  20843. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  20844. }
  20845. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  20846. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  20847. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  20848. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  20849. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  20850. this._subDiv.max = this._partitioningSubdivisions;
  20851. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  20852. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  20853. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  20854. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  20855. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  20856. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  20857. // set the parameters for ComputeNormals()
  20858. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  20859. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  20860. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  20861. this._facetParameters.bInfo = bInfo;
  20862. this._facetParameters.bbSize = this._bbSize;
  20863. this._facetParameters.subDiv = this._subDiv;
  20864. this._facetParameters.ratio = this.partitioningBBoxRatio;
  20865. this._facetParameters.depthSort = this._facetDepthSort;
  20866. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20867. this.computeWorldMatrix(true);
  20868. this._worldMatrix.invertToRef(this._invertedMatrix);
  20869. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  20870. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  20871. }
  20872. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  20873. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  20874. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20875. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  20876. var l = (this._depthSortedIndices.length / 3) | 0;
  20877. for (var f = 0; f < l; f++) {
  20878. var sind = this._depthSortedFacets[f].ind;
  20879. this._depthSortedIndices[f * 3] = indices[sind];
  20880. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  20881. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  20882. }
  20883. this.updateIndices(this._depthSortedIndices);
  20884. }
  20885. return this;
  20886. };
  20887. /**
  20888. * Returns the facetLocalNormals array.
  20889. * The normals are expressed in the mesh local spac
  20890. * @returns an array of Vector3
  20891. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20892. */
  20893. AbstractMesh.prototype.getFacetLocalNormals = function () {
  20894. if (!this._facetNormals) {
  20895. this.updateFacetData();
  20896. }
  20897. return this._facetNormals;
  20898. };
  20899. /**
  20900. * Returns the facetLocalPositions array.
  20901. * The facet positions are expressed in the mesh local space
  20902. * @returns an array of Vector3
  20903. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20904. */
  20905. AbstractMesh.prototype.getFacetLocalPositions = function () {
  20906. if (!this._facetPositions) {
  20907. this.updateFacetData();
  20908. }
  20909. return this._facetPositions;
  20910. };
  20911. /**
  20912. * Returns the facetLocalPartioning array
  20913. * @returns an array of array of numbers
  20914. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20915. */
  20916. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  20917. if (!this._facetPartitioning) {
  20918. this.updateFacetData();
  20919. }
  20920. return this._facetPartitioning;
  20921. };
  20922. /**
  20923. * Returns the i-th facet position in the world system.
  20924. * This method allocates a new Vector3 per call
  20925. * @param i defines the facet index
  20926. * @returns a new Vector3
  20927. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20928. */
  20929. AbstractMesh.prototype.getFacetPosition = function (i) {
  20930. var pos = BABYLON.Vector3.Zero();
  20931. this.getFacetPositionToRef(i, pos);
  20932. return pos;
  20933. };
  20934. /**
  20935. * Sets the reference Vector3 with the i-th facet position in the world system
  20936. * @param i defines the facet index
  20937. * @param ref defines the target vector
  20938. * @returns the current mesh
  20939. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20940. */
  20941. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  20942. var localPos = (this.getFacetLocalPositions())[i];
  20943. var world = this.getWorldMatrix();
  20944. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  20945. return this;
  20946. };
  20947. /**
  20948. * Returns the i-th facet normal in the world system.
  20949. * This method allocates a new Vector3 per call
  20950. * @param i defines the facet index
  20951. * @returns a new Vector3
  20952. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20953. */
  20954. AbstractMesh.prototype.getFacetNormal = function (i) {
  20955. var norm = BABYLON.Vector3.Zero();
  20956. this.getFacetNormalToRef(i, norm);
  20957. return norm;
  20958. };
  20959. /**
  20960. * Sets the reference Vector3 with the i-th facet normal in the world system
  20961. * @param i defines the facet index
  20962. * @param ref defines the target vector
  20963. * @returns the current mesh
  20964. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20965. */
  20966. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  20967. var localNorm = (this.getFacetLocalNormals())[i];
  20968. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  20969. return this;
  20970. };
  20971. /**
  20972. * 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)
  20973. * @param x defines x coordinate
  20974. * @param y defines y coordinate
  20975. * @param z defines z coordinate
  20976. * @returns the array of facet indexes
  20977. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20978. */
  20979. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  20980. var bInfo = this.getBoundingInfo();
  20981. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  20982. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  20983. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  20984. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  20985. return null;
  20986. }
  20987. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  20988. };
  20989. /**
  20990. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  20991. * @param projected sets as the (x,y,z) world projection on the facet
  20992. * @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
  20993. * @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
  20994. * @param x defines x coordinate
  20995. * @param y defines y coordinate
  20996. * @param z defines z coordinate
  20997. * @returns the face index if found (or null instead)
  20998. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20999. */
  21000. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21001. if (checkFace === void 0) { checkFace = false; }
  21002. if (facing === void 0) { facing = true; }
  21003. var world = this.getWorldMatrix();
  21004. var invMat = BABYLON.Tmp.Matrix[5];
  21005. world.invertToRef(invMat);
  21006. var invVect = BABYLON.Tmp.Vector3[8];
  21007. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21008. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21009. if (projected) {
  21010. // tranform the local computed projected vector to world coordinates
  21011. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21012. }
  21013. return closest;
  21014. };
  21015. /**
  21016. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21017. * @param projected sets as the (x,y,z) local projection on the facet
  21018. * @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
  21019. * @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
  21020. * @param x defines x coordinate
  21021. * @param y defines y coordinate
  21022. * @param z defines z coordinate
  21023. * @returns the face index if found (or null instead)
  21024. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21025. */
  21026. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21027. if (checkFace === void 0) { checkFace = false; }
  21028. if (facing === void 0) { facing = true; }
  21029. var closest = null;
  21030. var tmpx = 0.0;
  21031. var tmpy = 0.0;
  21032. var tmpz = 0.0;
  21033. var d = 0.0; // tmp dot facet normal * facet position
  21034. var t0 = 0.0;
  21035. var projx = 0.0;
  21036. var projy = 0.0;
  21037. var projz = 0.0;
  21038. // Get all the facets in the same partitioning block than (x, y, z)
  21039. var facetPositions = this.getFacetLocalPositions();
  21040. var facetNormals = this.getFacetLocalNormals();
  21041. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21042. if (!facetsInBlock) {
  21043. return null;
  21044. }
  21045. // Get the closest facet to (x, y, z)
  21046. var shortest = Number.MAX_VALUE; // init distance vars
  21047. var tmpDistance = shortest;
  21048. var fib; // current facet in the block
  21049. var norm; // current facet normal
  21050. var p0; // current facet barycenter position
  21051. // loop on all the facets in the current partitioning block
  21052. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21053. fib = facetsInBlock[idx];
  21054. norm = facetNormals[fib];
  21055. p0 = facetPositions[fib];
  21056. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21057. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21058. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21059. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21060. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21061. projx = x + norm.x * t0;
  21062. projy = y + norm.y * t0;
  21063. projz = z + norm.z * t0;
  21064. tmpx = projx - x;
  21065. tmpy = projy - y;
  21066. tmpz = projz - z;
  21067. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21068. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21069. shortest = tmpDistance;
  21070. closest = fib;
  21071. if (projected) {
  21072. projected.x = projx;
  21073. projected.y = projy;
  21074. projected.z = projz;
  21075. }
  21076. }
  21077. }
  21078. }
  21079. return closest;
  21080. };
  21081. /**
  21082. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21083. * @returns the parameters
  21084. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21085. */
  21086. AbstractMesh.prototype.getFacetDataParameters = function () {
  21087. return this._facetParameters;
  21088. };
  21089. /**
  21090. * Disables the feature FacetData and frees the related memory
  21091. * @returns the current mesh
  21092. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21093. */
  21094. AbstractMesh.prototype.disableFacetData = function () {
  21095. if (this._facetDataEnabled) {
  21096. this._facetDataEnabled = false;
  21097. this._facetPositions = new Array();
  21098. this._facetNormals = new Array();
  21099. this._facetPartitioning = new Array();
  21100. this._facetParameters = null;
  21101. this._depthSortedIndices = new Uint32Array(0);
  21102. }
  21103. return this;
  21104. };
  21105. /**
  21106. * Updates the AbstractMesh indices array
  21107. * @param indices defines the data source
  21108. * @returns the current mesh
  21109. */
  21110. AbstractMesh.prototype.updateIndices = function (indices) {
  21111. return this;
  21112. };
  21113. /**
  21114. * Creates new normals data for the mesh
  21115. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21116. * @returns the current mesh
  21117. */
  21118. AbstractMesh.prototype.createNormals = function (updatable) {
  21119. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21120. var indices = this.getIndices();
  21121. var normals;
  21122. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21123. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21124. }
  21125. else {
  21126. normals = [];
  21127. }
  21128. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21129. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21130. return this;
  21131. };
  21132. /**
  21133. * Align the mesh with a normal
  21134. * @param normal defines the normal to use
  21135. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21136. * @returns the current mesh
  21137. */
  21138. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21139. if (!upDirection) {
  21140. upDirection = BABYLON.Axis.Y;
  21141. }
  21142. var axisX = BABYLON.Tmp.Vector3[0];
  21143. var axisZ = BABYLON.Tmp.Vector3[1];
  21144. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21145. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21146. if (this.rotationQuaternion) {
  21147. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21148. }
  21149. else {
  21150. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21151. }
  21152. return this;
  21153. };
  21154. /** @hidden */
  21155. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21156. var engine = this.getEngine();
  21157. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  21158. this._isOccluded = false;
  21159. return;
  21160. }
  21161. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  21162. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  21163. if (isOcclusionQueryAvailable) {
  21164. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  21165. this._isOcclusionQueryInProgress = false;
  21166. this._occlusionInternalRetryCounter = 0;
  21167. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  21168. }
  21169. else {
  21170. this._occlusionInternalRetryCounter++;
  21171. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  21172. this._isOcclusionQueryInProgress = false;
  21173. this._occlusionInternalRetryCounter = 0;
  21174. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  21175. // if strict continue the last state of the object.
  21176. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  21177. }
  21178. else {
  21179. return;
  21180. }
  21181. }
  21182. }
  21183. var scene = this.getScene();
  21184. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  21185. if (!this._occlusionQuery) {
  21186. this._occlusionQuery = engine.createQuery();
  21187. }
  21188. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  21189. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  21190. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  21191. this._isOcclusionQueryInProgress = true;
  21192. };
  21193. /** No occlusion */
  21194. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21195. /** Occlusion set to optimisitic */
  21196. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21197. /** Occlusion set to strict */
  21198. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21199. /** Use an accurante occlusion algorithm */
  21200. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21201. /** Use a conservative occlusion algorithm */
  21202. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21203. return AbstractMesh;
  21204. }(BABYLON.TransformNode));
  21205. BABYLON.AbstractMesh = AbstractMesh;
  21206. })(BABYLON || (BABYLON = {}));
  21207. //# sourceMappingURL=babylon.abstractMesh.js.map
  21208. var BABYLON;
  21209. (function (BABYLON) {
  21210. /**
  21211. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21212. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21213. * 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.
  21214. */
  21215. var Light = /** @class */ (function (_super) {
  21216. __extends(Light, _super);
  21217. /**
  21218. * Creates a Light object in the scene.
  21219. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21220. * @param name The firendly name of the light
  21221. * @param scene The scene the light belongs too
  21222. */
  21223. function Light(name, scene) {
  21224. var _this = _super.call(this, name, scene) || this;
  21225. /**
  21226. * Diffuse gives the basic color to an object.
  21227. */
  21228. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21229. /**
  21230. * Specular produces a highlight color on an object.
  21231. * Note: This is note affecting PBR materials.
  21232. */
  21233. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21234. /**
  21235. * Strength of the light.
  21236. * Note: By default it is define in the framework own unit.
  21237. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21238. */
  21239. _this.intensity = 1.0;
  21240. /**
  21241. * Defines how far from the source the light is impacting in scene units.
  21242. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21243. */
  21244. _this.range = Number.MAX_VALUE;
  21245. /**
  21246. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21247. * of light.
  21248. */
  21249. _this._photometricScale = 1.0;
  21250. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21251. _this._radius = 0.00001;
  21252. /**
  21253. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21254. * exceeding the number allowed of the materials.
  21255. */
  21256. _this.renderPriority = 0;
  21257. /**
  21258. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21259. * the current shadow generator.
  21260. */
  21261. _this.shadowEnabled = true;
  21262. _this._excludeWithLayerMask = 0;
  21263. _this._includeOnlyWithLayerMask = 0;
  21264. _this._lightmapMode = 0;
  21265. /**
  21266. * @hidden Internal use only.
  21267. */
  21268. _this._excludedMeshesIds = new Array();
  21269. /**
  21270. * @hidden Internal use only.
  21271. */
  21272. _this._includedOnlyMeshesIds = new Array();
  21273. _this.getScene().addLight(_this);
  21274. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21275. _this._buildUniformLayout();
  21276. _this.includedOnlyMeshes = new Array();
  21277. _this.excludedMeshes = new Array();
  21278. _this._resyncMeshes();
  21279. return _this;
  21280. }
  21281. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  21282. /**
  21283. * If every light affecting the material is in this lightmapMode,
  21284. * material.lightmapTexture adds or multiplies
  21285. * (depends on material.useLightmapAsShadowmap)
  21286. * after every other light calculations.
  21287. */
  21288. get: function () {
  21289. return Light._LIGHTMAP_DEFAULT;
  21290. },
  21291. enumerable: true,
  21292. configurable: true
  21293. });
  21294. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  21295. /**
  21296. * material.lightmapTexture as only diffuse lighting from this light
  21297. * adds only specular lighting from this light
  21298. * adds dynamic shadows
  21299. */
  21300. get: function () {
  21301. return Light._LIGHTMAP_SPECULAR;
  21302. },
  21303. enumerable: true,
  21304. configurable: true
  21305. });
  21306. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  21307. /**
  21308. * material.lightmapTexture as only lighting
  21309. * no light calculation from this light
  21310. * only adds dynamic shadows from this light
  21311. */
  21312. get: function () {
  21313. return Light._LIGHTMAP_SHADOWSONLY;
  21314. },
  21315. enumerable: true,
  21316. configurable: true
  21317. });
  21318. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  21319. /**
  21320. * Each light type uses the default quantity according to its type:
  21321. * point/spot lights use luminous intensity
  21322. * directional lights use illuminance
  21323. */
  21324. get: function () {
  21325. return Light._INTENSITYMODE_AUTOMATIC;
  21326. },
  21327. enumerable: true,
  21328. configurable: true
  21329. });
  21330. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  21331. /**
  21332. * lumen (lm)
  21333. */
  21334. get: function () {
  21335. return Light._INTENSITYMODE_LUMINOUSPOWER;
  21336. },
  21337. enumerable: true,
  21338. configurable: true
  21339. });
  21340. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  21341. /**
  21342. * candela (lm/sr)
  21343. */
  21344. get: function () {
  21345. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  21346. },
  21347. enumerable: true,
  21348. configurable: true
  21349. });
  21350. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  21351. /**
  21352. * lux (lm/m^2)
  21353. */
  21354. get: function () {
  21355. return Light._INTENSITYMODE_ILLUMINANCE;
  21356. },
  21357. enumerable: true,
  21358. configurable: true
  21359. });
  21360. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  21361. /**
  21362. * nit (cd/m^2)
  21363. */
  21364. get: function () {
  21365. return Light._INTENSITYMODE_LUMINANCE;
  21366. },
  21367. enumerable: true,
  21368. configurable: true
  21369. });
  21370. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  21371. /**
  21372. * Light type const id of the point light.
  21373. */
  21374. get: function () {
  21375. return Light._LIGHTTYPEID_POINTLIGHT;
  21376. },
  21377. enumerable: true,
  21378. configurable: true
  21379. });
  21380. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  21381. /**
  21382. * Light type const id of the directional light.
  21383. */
  21384. get: function () {
  21385. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  21386. },
  21387. enumerable: true,
  21388. configurable: true
  21389. });
  21390. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  21391. /**
  21392. * Light type const id of the spot light.
  21393. */
  21394. get: function () {
  21395. return Light._LIGHTTYPEID_SPOTLIGHT;
  21396. },
  21397. enumerable: true,
  21398. configurable: true
  21399. });
  21400. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  21401. /**
  21402. * Light type const id of the hemispheric light.
  21403. */
  21404. get: function () {
  21405. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  21406. },
  21407. enumerable: true,
  21408. configurable: true
  21409. });
  21410. Object.defineProperty(Light.prototype, "intensityMode", {
  21411. /**
  21412. * Gets the photometric scale used to interpret the intensity.
  21413. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21414. */
  21415. get: function () {
  21416. return this._intensityMode;
  21417. },
  21418. /**
  21419. * Sets the photometric scale used to interpret the intensity.
  21420. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21421. */
  21422. set: function (value) {
  21423. this._intensityMode = value;
  21424. this._computePhotometricScale();
  21425. },
  21426. enumerable: true,
  21427. configurable: true
  21428. });
  21429. ;
  21430. ;
  21431. Object.defineProperty(Light.prototype, "radius", {
  21432. /**
  21433. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21434. */
  21435. get: function () {
  21436. return this._radius;
  21437. },
  21438. /**
  21439. * sets the light radius used by PBR Materials to simulate soft area lights.
  21440. */
  21441. set: function (value) {
  21442. this._radius = value;
  21443. this._computePhotometricScale();
  21444. },
  21445. enumerable: true,
  21446. configurable: true
  21447. });
  21448. ;
  21449. ;
  21450. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21451. /**
  21452. * Gets the only meshes impacted by this light.
  21453. */
  21454. get: function () {
  21455. return this._includedOnlyMeshes;
  21456. },
  21457. /**
  21458. * Sets the only meshes impacted by this light.
  21459. */
  21460. set: function (value) {
  21461. this._includedOnlyMeshes = value;
  21462. this._hookArrayForIncludedOnly(value);
  21463. },
  21464. enumerable: true,
  21465. configurable: true
  21466. });
  21467. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21468. /**
  21469. * Gets the meshes not impacted by this light.
  21470. */
  21471. get: function () {
  21472. return this._excludedMeshes;
  21473. },
  21474. /**
  21475. * Sets the meshes not impacted by this light.
  21476. */
  21477. set: function (value) {
  21478. this._excludedMeshes = value;
  21479. this._hookArrayForExcluded(value);
  21480. },
  21481. enumerable: true,
  21482. configurable: true
  21483. });
  21484. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21485. /**
  21486. * Gets the layer id use to find what meshes are not impacted by the light.
  21487. * Inactive if 0
  21488. */
  21489. get: function () {
  21490. return this._excludeWithLayerMask;
  21491. },
  21492. /**
  21493. * Sets the layer id use to find what meshes are not impacted by the light.
  21494. * Inactive if 0
  21495. */
  21496. set: function (value) {
  21497. this._excludeWithLayerMask = value;
  21498. this._resyncMeshes();
  21499. },
  21500. enumerable: true,
  21501. configurable: true
  21502. });
  21503. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21504. /**
  21505. * Gets the layer id use to find what meshes are impacted by the light.
  21506. * Inactive if 0
  21507. */
  21508. get: function () {
  21509. return this._includeOnlyWithLayerMask;
  21510. },
  21511. /**
  21512. * Sets the layer id use to find what meshes are impacted by the light.
  21513. * Inactive if 0
  21514. */
  21515. set: function (value) {
  21516. this._includeOnlyWithLayerMask = value;
  21517. this._resyncMeshes();
  21518. },
  21519. enumerable: true,
  21520. configurable: true
  21521. });
  21522. Object.defineProperty(Light.prototype, "lightmapMode", {
  21523. /**
  21524. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21525. */
  21526. get: function () {
  21527. return this._lightmapMode;
  21528. },
  21529. /**
  21530. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21531. */
  21532. set: function (value) {
  21533. if (this._lightmapMode === value) {
  21534. return;
  21535. }
  21536. this._lightmapMode = value;
  21537. this._markMeshesAsLightDirty();
  21538. },
  21539. enumerable: true,
  21540. configurable: true
  21541. });
  21542. /**
  21543. * Returns the string "Light".
  21544. * @returns the class name
  21545. */
  21546. Light.prototype.getClassName = function () {
  21547. return "Light";
  21548. };
  21549. /**
  21550. * Converts the light information to a readable string for debug purpose.
  21551. * @param fullDetails Supports for multiple levels of logging within scene loading
  21552. * @returns the human readable light info
  21553. */
  21554. Light.prototype.toString = function (fullDetails) {
  21555. var ret = "Name: " + this.name;
  21556. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21557. if (this.animations) {
  21558. for (var i = 0; i < this.animations.length; i++) {
  21559. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21560. }
  21561. }
  21562. if (fullDetails) {
  21563. }
  21564. return ret;
  21565. };
  21566. /**
  21567. * Set the enabled state of this node.
  21568. * @param value - the new enabled state
  21569. */
  21570. Light.prototype.setEnabled = function (value) {
  21571. _super.prototype.setEnabled.call(this, value);
  21572. this._resyncMeshes();
  21573. };
  21574. /**
  21575. * Returns the Light associated shadow generator if any.
  21576. * @return the associated shadow generator.
  21577. */
  21578. Light.prototype.getShadowGenerator = function () {
  21579. return this._shadowGenerator;
  21580. };
  21581. /**
  21582. * Returns a Vector3, the absolute light position in the World.
  21583. * @returns the world space position of the light
  21584. */
  21585. Light.prototype.getAbsolutePosition = function () {
  21586. return BABYLON.Vector3.Zero();
  21587. };
  21588. /**
  21589. * Specifies if the light will affect the passed mesh.
  21590. * @param mesh The mesh to test against the light
  21591. * @return true the mesh is affected otherwise, false.
  21592. */
  21593. Light.prototype.canAffectMesh = function (mesh) {
  21594. if (!mesh) {
  21595. return true;
  21596. }
  21597. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21598. return false;
  21599. }
  21600. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21601. return false;
  21602. }
  21603. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21604. return false;
  21605. }
  21606. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21607. return false;
  21608. }
  21609. return true;
  21610. };
  21611. /**
  21612. * Computes and Returns the light World matrix.
  21613. * @returns the world matrix
  21614. */
  21615. Light.prototype.getWorldMatrix = function () {
  21616. this._currentRenderId = this.getScene().getRenderId();
  21617. this._childRenderId = this._currentRenderId;
  21618. var worldMatrix = this._getWorldMatrix();
  21619. if (this.parent && this.parent.getWorldMatrix) {
  21620. if (!this._parentedWorldMatrix) {
  21621. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  21622. }
  21623. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  21624. this._markSyncedWithParent();
  21625. return this._parentedWorldMatrix;
  21626. }
  21627. return worldMatrix;
  21628. };
  21629. /**
  21630. * Sort function to order lights for rendering.
  21631. * @param a First Light object to compare to second.
  21632. * @param b Second Light object to compare first.
  21633. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21634. */
  21635. Light.CompareLightsPriority = function (a, b) {
  21636. //shadow-casting lights have priority over non-shadow-casting lights
  21637. //the renderPrioirty is a secondary sort criterion
  21638. if (a.shadowEnabled !== b.shadowEnabled) {
  21639. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21640. }
  21641. return b.renderPriority - a.renderPriority;
  21642. };
  21643. /**
  21644. * Releases resources associated with this node.
  21645. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21646. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21647. */
  21648. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21649. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21650. if (this._shadowGenerator) {
  21651. this._shadowGenerator.dispose();
  21652. this._shadowGenerator = null;
  21653. }
  21654. // Animations
  21655. this.getScene().stopAnimation(this);
  21656. // Remove from meshes
  21657. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21658. var mesh = _a[_i];
  21659. mesh._removeLightSource(this);
  21660. }
  21661. this._uniformBuffer.dispose();
  21662. // Remove from scene
  21663. this.getScene().removeLight(this);
  21664. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21665. };
  21666. /**
  21667. * Returns the light type ID (integer).
  21668. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21669. */
  21670. Light.prototype.getTypeID = function () {
  21671. return 0;
  21672. };
  21673. /**
  21674. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21675. * @returns the scaled intensity in intensity mode unit
  21676. */
  21677. Light.prototype.getScaledIntensity = function () {
  21678. return this._photometricScale * this.intensity;
  21679. };
  21680. /**
  21681. * Returns a new Light object, named "name", from the current one.
  21682. * @param name The name of the cloned light
  21683. * @returns the new created light
  21684. */
  21685. Light.prototype.clone = function (name) {
  21686. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21687. if (!constructor) {
  21688. return null;
  21689. }
  21690. return BABYLON.SerializationHelper.Clone(constructor, this);
  21691. };
  21692. /**
  21693. * Serializes the current light into a Serialization object.
  21694. * @returns the serialized object.
  21695. */
  21696. Light.prototype.serialize = function () {
  21697. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21698. // Type
  21699. serializationObject.type = this.getTypeID();
  21700. // Parent
  21701. if (this.parent) {
  21702. serializationObject.parentId = this.parent.id;
  21703. }
  21704. // Inclusion / exclusions
  21705. if (this.excludedMeshes.length > 0) {
  21706. serializationObject.excludedMeshesIds = [];
  21707. this.excludedMeshes.forEach(function (mesh) {
  21708. serializationObject.excludedMeshesIds.push(mesh.id);
  21709. });
  21710. }
  21711. if (this.includedOnlyMeshes.length > 0) {
  21712. serializationObject.includedOnlyMeshesIds = [];
  21713. this.includedOnlyMeshes.forEach(function (mesh) {
  21714. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  21715. });
  21716. }
  21717. // Animations
  21718. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21719. serializationObject.ranges = this.serializeAnimationRanges();
  21720. return serializationObject;
  21721. };
  21722. /**
  21723. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  21724. * This new light is named "name" and added to the passed scene.
  21725. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  21726. * @param name The friendly name of the light
  21727. * @param scene The scene the new light will belong to
  21728. * @returns the constructor function
  21729. */
  21730. Light.GetConstructorFromName = function (type, name, scene) {
  21731. switch (type) {
  21732. case 0:
  21733. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  21734. case 1:
  21735. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  21736. case 2:
  21737. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  21738. case 3:
  21739. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  21740. }
  21741. return null;
  21742. };
  21743. /**
  21744. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  21745. * @param parsedLight The JSON representation of the light
  21746. * @param scene The scene to create the parsed light in
  21747. * @returns the created light after parsing
  21748. */
  21749. Light.Parse = function (parsedLight, scene) {
  21750. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  21751. if (!constructor) {
  21752. return null;
  21753. }
  21754. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  21755. // Inclusion / exclusions
  21756. if (parsedLight.excludedMeshesIds) {
  21757. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  21758. }
  21759. if (parsedLight.includedOnlyMeshesIds) {
  21760. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  21761. }
  21762. // Parent
  21763. if (parsedLight.parentId) {
  21764. light._waitingParentId = parsedLight.parentId;
  21765. }
  21766. // Animations
  21767. if (parsedLight.animations) {
  21768. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  21769. var parsedAnimation = parsedLight.animations[animationIndex];
  21770. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21771. }
  21772. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  21773. }
  21774. if (parsedLight.autoAnimate) {
  21775. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  21776. }
  21777. return light;
  21778. };
  21779. Light.prototype._hookArrayForExcluded = function (array) {
  21780. var _this = this;
  21781. var oldPush = array.push;
  21782. array.push = function () {
  21783. var items = [];
  21784. for (var _i = 0; _i < arguments.length; _i++) {
  21785. items[_i] = arguments[_i];
  21786. }
  21787. var result = oldPush.apply(array, items);
  21788. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  21789. var item = items_1[_a];
  21790. item._resyncLighSource(_this);
  21791. }
  21792. return result;
  21793. };
  21794. var oldSplice = array.splice;
  21795. array.splice = function (index, deleteCount) {
  21796. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21797. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  21798. var item = deleted_1[_i];
  21799. item._resyncLighSource(_this);
  21800. }
  21801. return deleted;
  21802. };
  21803. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  21804. var item = array_1[_i];
  21805. item._resyncLighSource(this);
  21806. }
  21807. };
  21808. Light.prototype._hookArrayForIncludedOnly = function (array) {
  21809. var _this = this;
  21810. var oldPush = array.push;
  21811. array.push = function () {
  21812. var items = [];
  21813. for (var _i = 0; _i < arguments.length; _i++) {
  21814. items[_i] = arguments[_i];
  21815. }
  21816. var result = oldPush.apply(array, items);
  21817. _this._resyncMeshes();
  21818. return result;
  21819. };
  21820. var oldSplice = array.splice;
  21821. array.splice = function (index, deleteCount) {
  21822. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21823. _this._resyncMeshes();
  21824. return deleted;
  21825. };
  21826. this._resyncMeshes();
  21827. };
  21828. Light.prototype._resyncMeshes = function () {
  21829. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21830. var mesh = _a[_i];
  21831. mesh._resyncLighSource(this);
  21832. }
  21833. };
  21834. /**
  21835. * Forces the meshes to update their light related information in their rendering used effects
  21836. * @hidden Internal Use Only
  21837. */
  21838. Light.prototype._markMeshesAsLightDirty = function () {
  21839. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21840. var mesh = _a[_i];
  21841. if (mesh._lightSources.indexOf(this) !== -1) {
  21842. mesh._markSubMeshesAsLightDirty();
  21843. }
  21844. }
  21845. };
  21846. /**
  21847. * Recomputes the cached photometric scale if needed.
  21848. */
  21849. Light.prototype._computePhotometricScale = function () {
  21850. this._photometricScale = this._getPhotometricScale();
  21851. this.getScene().resetCachedMaterial();
  21852. };
  21853. /**
  21854. * Returns the Photometric Scale according to the light type and intensity mode.
  21855. */
  21856. Light.prototype._getPhotometricScale = function () {
  21857. var photometricScale = 0.0;
  21858. var lightTypeID = this.getTypeID();
  21859. //get photometric mode
  21860. var photometricMode = this.intensityMode;
  21861. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  21862. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  21863. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  21864. }
  21865. else {
  21866. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  21867. }
  21868. }
  21869. //compute photometric scale
  21870. switch (lightTypeID) {
  21871. case Light.LIGHTTYPEID_POINTLIGHT:
  21872. case Light.LIGHTTYPEID_SPOTLIGHT:
  21873. switch (photometricMode) {
  21874. case Light.INTENSITYMODE_LUMINOUSPOWER:
  21875. photometricScale = 1.0 / (4.0 * Math.PI);
  21876. break;
  21877. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  21878. photometricScale = 1.0;
  21879. break;
  21880. case Light.INTENSITYMODE_LUMINANCE:
  21881. photometricScale = this.radius * this.radius;
  21882. break;
  21883. }
  21884. break;
  21885. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  21886. switch (photometricMode) {
  21887. case Light.INTENSITYMODE_ILLUMINANCE:
  21888. photometricScale = 1.0;
  21889. break;
  21890. case Light.INTENSITYMODE_LUMINANCE:
  21891. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  21892. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  21893. var apexAngleRadians = this.radius;
  21894. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  21895. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  21896. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  21897. photometricScale = solidAngle;
  21898. break;
  21899. }
  21900. break;
  21901. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  21902. // No fall off in hemisperic light.
  21903. photometricScale = 1.0;
  21904. break;
  21905. }
  21906. return photometricScale;
  21907. };
  21908. /**
  21909. * Reorder the light in the scene according to their defined priority.
  21910. * @hidden Internal Use Only
  21911. */
  21912. Light.prototype._reorderLightsInScene = function () {
  21913. var scene = this.getScene();
  21914. if (this._renderPriority != 0) {
  21915. scene.requireLightSorting = true;
  21916. }
  21917. this.getScene().sortLightsByPriority();
  21918. };
  21919. //lightmapMode Consts
  21920. Light._LIGHTMAP_DEFAULT = 0;
  21921. Light._LIGHTMAP_SPECULAR = 1;
  21922. Light._LIGHTMAP_SHADOWSONLY = 2;
  21923. // Intensity Mode Consts
  21924. Light._INTENSITYMODE_AUTOMATIC = 0;
  21925. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  21926. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  21927. Light._INTENSITYMODE_ILLUMINANCE = 3;
  21928. Light._INTENSITYMODE_LUMINANCE = 4;
  21929. // Light types ids const.
  21930. Light._LIGHTTYPEID_POINTLIGHT = 0;
  21931. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  21932. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  21933. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  21934. __decorate([
  21935. BABYLON.serializeAsColor3()
  21936. ], Light.prototype, "diffuse", void 0);
  21937. __decorate([
  21938. BABYLON.serializeAsColor3()
  21939. ], Light.prototype, "specular", void 0);
  21940. __decorate([
  21941. BABYLON.serialize()
  21942. ], Light.prototype, "intensity", void 0);
  21943. __decorate([
  21944. BABYLON.serialize()
  21945. ], Light.prototype, "range", void 0);
  21946. __decorate([
  21947. BABYLON.serialize()
  21948. ], Light.prototype, "intensityMode", null);
  21949. __decorate([
  21950. BABYLON.serialize()
  21951. ], Light.prototype, "radius", null);
  21952. __decorate([
  21953. BABYLON.serialize()
  21954. ], Light.prototype, "_renderPriority", void 0);
  21955. __decorate([
  21956. BABYLON.expandToProperty("_reorderLightsInScene")
  21957. ], Light.prototype, "renderPriority", void 0);
  21958. __decorate([
  21959. BABYLON.serialize()
  21960. ], Light.prototype, "shadowEnabled", void 0);
  21961. __decorate([
  21962. BABYLON.serialize("excludeWithLayerMask")
  21963. ], Light.prototype, "_excludeWithLayerMask", void 0);
  21964. __decorate([
  21965. BABYLON.serialize("includeOnlyWithLayerMask")
  21966. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  21967. __decorate([
  21968. BABYLON.serialize("lightmapMode")
  21969. ], Light.prototype, "_lightmapMode", void 0);
  21970. return Light;
  21971. }(BABYLON.Node));
  21972. BABYLON.Light = Light;
  21973. })(BABYLON || (BABYLON = {}));
  21974. //# sourceMappingURL=babylon.light.js.map
  21975. var BABYLON;
  21976. (function (BABYLON) {
  21977. var Camera = /** @class */ (function (_super) {
  21978. __extends(Camera, _super);
  21979. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  21980. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  21981. var _this = _super.call(this, name, scene) || this;
  21982. /**
  21983. * The vector the camera should consider as up.
  21984. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  21985. */
  21986. _this.upVector = BABYLON.Vector3.Up();
  21987. _this.orthoLeft = null;
  21988. _this.orthoRight = null;
  21989. _this.orthoBottom = null;
  21990. _this.orthoTop = null;
  21991. /**
  21992. * FOV is set in Radians. (default is 0.8)
  21993. */
  21994. _this.fov = 0.8;
  21995. _this.minZ = 1;
  21996. _this.maxZ = 10000.0;
  21997. _this.inertia = 0.9;
  21998. _this.mode = Camera.PERSPECTIVE_CAMERA;
  21999. _this.isIntermediate = false;
  22000. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  22001. /**
  22002. * Restricts the camera to viewing objects with the same layerMask.
  22003. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  22004. */
  22005. _this.layerMask = 0x0FFFFFFF;
  22006. /**
  22007. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  22008. */
  22009. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  22010. // Camera rig members
  22011. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  22012. _this._rigCameras = new Array();
  22013. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  22014. _this._skipRendering = false;
  22015. _this.customRenderTargets = new Array();
  22016. // Observables
  22017. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  22018. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  22019. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  22020. _this.onRestoreStateObservable = new BABYLON.Observable();
  22021. // Cache
  22022. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22023. _this._projectionMatrix = new BABYLON.Matrix();
  22024. _this._doNotComputeProjectionMatrix = false;
  22025. _this._worldMatrix = BABYLON.Matrix.Identity();
  22026. _this._postProcesses = new Array();
  22027. _this._transformMatrix = BABYLON.Matrix.Zero();
  22028. _this._activeMeshes = new BABYLON.SmartArray(256);
  22029. _this._globalPosition = BABYLON.Vector3.Zero();
  22030. _this._refreshFrustumPlanes = true;
  22031. _this.getScene().addCamera(_this);
  22032. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22033. _this.getScene().activeCamera = _this;
  22034. }
  22035. _this.position = position;
  22036. return _this;
  22037. }
  22038. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  22039. get: function () {
  22040. return Camera._PERSPECTIVE_CAMERA;
  22041. },
  22042. enumerable: true,
  22043. configurable: true
  22044. });
  22045. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  22046. get: function () {
  22047. return Camera._ORTHOGRAPHIC_CAMERA;
  22048. },
  22049. enumerable: true,
  22050. configurable: true
  22051. });
  22052. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  22053. /**
  22054. * This is the default FOV mode for perspective cameras.
  22055. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  22056. *
  22057. */
  22058. get: function () {
  22059. return Camera._FOVMODE_VERTICAL_FIXED;
  22060. },
  22061. enumerable: true,
  22062. configurable: true
  22063. });
  22064. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  22065. /**
  22066. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  22067. *
  22068. */
  22069. get: function () {
  22070. return Camera._FOVMODE_HORIZONTAL_FIXED;
  22071. },
  22072. enumerable: true,
  22073. configurable: true
  22074. });
  22075. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  22076. get: function () {
  22077. return Camera._RIG_MODE_NONE;
  22078. },
  22079. enumerable: true,
  22080. configurable: true
  22081. });
  22082. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  22083. get: function () {
  22084. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  22085. },
  22086. enumerable: true,
  22087. configurable: true
  22088. });
  22089. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  22090. get: function () {
  22091. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  22092. },
  22093. enumerable: true,
  22094. configurable: true
  22095. });
  22096. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  22097. get: function () {
  22098. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22099. },
  22100. enumerable: true,
  22101. configurable: true
  22102. });
  22103. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  22104. get: function () {
  22105. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  22106. },
  22107. enumerable: true,
  22108. configurable: true
  22109. });
  22110. Object.defineProperty(Camera, "RIG_MODE_VR", {
  22111. get: function () {
  22112. return Camera._RIG_MODE_VR;
  22113. },
  22114. enumerable: true,
  22115. configurable: true
  22116. });
  22117. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  22118. get: function () {
  22119. return Camera._RIG_MODE_WEBVR;
  22120. },
  22121. enumerable: true,
  22122. configurable: true
  22123. });
  22124. /**
  22125. * Store current camera state (fov, position, etc..)
  22126. */
  22127. Camera.prototype.storeState = function () {
  22128. this._stateStored = true;
  22129. this._storedFov = this.fov;
  22130. return this;
  22131. };
  22132. /**
  22133. * Restores the camera state values if it has been stored. You must call storeState() first
  22134. */
  22135. Camera.prototype._restoreStateValues = function () {
  22136. if (!this._stateStored) {
  22137. return false;
  22138. }
  22139. this.fov = this._storedFov;
  22140. return true;
  22141. };
  22142. /**
  22143. * Restored camera state. You must call storeState() first
  22144. */
  22145. Camera.prototype.restoreState = function () {
  22146. if (this._restoreStateValues()) {
  22147. this.onRestoreStateObservable.notifyObservers(this);
  22148. return true;
  22149. }
  22150. return false;
  22151. };
  22152. Camera.prototype.getClassName = function () {
  22153. return "Camera";
  22154. };
  22155. /**
  22156. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22157. */
  22158. Camera.prototype.toString = function (fullDetails) {
  22159. var ret = "Name: " + this.name;
  22160. ret += ", type: " + this.getClassName();
  22161. if (this.animations) {
  22162. for (var i = 0; i < this.animations.length; i++) {
  22163. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22164. }
  22165. }
  22166. if (fullDetails) {
  22167. }
  22168. return ret;
  22169. };
  22170. Object.defineProperty(Camera.prototype, "globalPosition", {
  22171. get: function () {
  22172. return this._globalPosition;
  22173. },
  22174. enumerable: true,
  22175. configurable: true
  22176. });
  22177. Camera.prototype.getActiveMeshes = function () {
  22178. return this._activeMeshes;
  22179. };
  22180. Camera.prototype.isActiveMesh = function (mesh) {
  22181. return (this._activeMeshes.indexOf(mesh) !== -1);
  22182. };
  22183. /**
  22184. * Is this camera ready to be used/rendered
  22185. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22186. * @return true if the camera is ready
  22187. */
  22188. Camera.prototype.isReady = function (completeCheck) {
  22189. if (completeCheck === void 0) { completeCheck = false; }
  22190. if (completeCheck) {
  22191. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22192. var pp = _a[_i];
  22193. if (pp && !pp.isReady()) {
  22194. return false;
  22195. }
  22196. }
  22197. }
  22198. return _super.prototype.isReady.call(this, completeCheck);
  22199. };
  22200. //Cache
  22201. Camera.prototype._initCache = function () {
  22202. _super.prototype._initCache.call(this);
  22203. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22204. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22205. this._cache.mode = undefined;
  22206. this._cache.minZ = undefined;
  22207. this._cache.maxZ = undefined;
  22208. this._cache.fov = undefined;
  22209. this._cache.fovMode = undefined;
  22210. this._cache.aspectRatio = undefined;
  22211. this._cache.orthoLeft = undefined;
  22212. this._cache.orthoRight = undefined;
  22213. this._cache.orthoBottom = undefined;
  22214. this._cache.orthoTop = undefined;
  22215. this._cache.renderWidth = undefined;
  22216. this._cache.renderHeight = undefined;
  22217. };
  22218. Camera.prototype._updateCache = function (ignoreParentClass) {
  22219. if (!ignoreParentClass) {
  22220. _super.prototype._updateCache.call(this);
  22221. }
  22222. this._cache.position.copyFrom(this.position);
  22223. this._cache.upVector.copyFrom(this.upVector);
  22224. };
  22225. // Synchronized
  22226. Camera.prototype._isSynchronized = function () {
  22227. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22228. };
  22229. Camera.prototype._isSynchronizedViewMatrix = function () {
  22230. if (!_super.prototype._isSynchronized.call(this))
  22231. return false;
  22232. return this._cache.position.equals(this.position)
  22233. && this._cache.upVector.equals(this.upVector)
  22234. && this.isSynchronizedWithParent();
  22235. };
  22236. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22237. var check = this._cache.mode === this.mode
  22238. && this._cache.minZ === this.minZ
  22239. && this._cache.maxZ === this.maxZ;
  22240. if (!check) {
  22241. return false;
  22242. }
  22243. var engine = this.getEngine();
  22244. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22245. check = this._cache.fov === this.fov
  22246. && this._cache.fovMode === this.fovMode
  22247. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22248. }
  22249. else {
  22250. check = this._cache.orthoLeft === this.orthoLeft
  22251. && this._cache.orthoRight === this.orthoRight
  22252. && this._cache.orthoBottom === this.orthoBottom
  22253. && this._cache.orthoTop === this.orthoTop
  22254. && this._cache.renderWidth === engine.getRenderWidth()
  22255. && this._cache.renderHeight === engine.getRenderHeight();
  22256. }
  22257. return check;
  22258. };
  22259. // Controls
  22260. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22261. };
  22262. Camera.prototype.detachControl = function (element) {
  22263. };
  22264. Camera.prototype.update = function () {
  22265. this._checkInputs();
  22266. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22267. this._updateRigCameras();
  22268. }
  22269. };
  22270. Camera.prototype._checkInputs = function () {
  22271. this.onAfterCheckInputsObservable.notifyObservers(this);
  22272. };
  22273. Object.defineProperty(Camera.prototype, "rigCameras", {
  22274. get: function () {
  22275. return this._rigCameras;
  22276. },
  22277. enumerable: true,
  22278. configurable: true
  22279. });
  22280. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22281. get: function () {
  22282. return this._rigPostProcess;
  22283. },
  22284. enumerable: true,
  22285. configurable: true
  22286. });
  22287. /**
  22288. * Internal, gets the first post proces.
  22289. * @returns the first post process to be run on this camera.
  22290. */
  22291. Camera.prototype._getFirstPostProcess = function () {
  22292. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22293. if (this._postProcesses[ppIndex] !== null) {
  22294. return this._postProcesses[ppIndex];
  22295. }
  22296. }
  22297. return null;
  22298. };
  22299. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22300. // invalidate framebuffer
  22301. var firstPostProcess = this._getFirstPostProcess();
  22302. if (firstPostProcess) {
  22303. firstPostProcess.markTextureDirty();
  22304. }
  22305. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22306. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22307. var cam = this._rigCameras[i];
  22308. var rigPostProcess = cam._rigPostProcess;
  22309. // for VR rig, there does not have to be a post process
  22310. if (rigPostProcess) {
  22311. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22312. if (isPass) {
  22313. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22314. cam.isIntermediate = this._postProcesses.length === 0;
  22315. }
  22316. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22317. rigPostProcess.markTextureDirty();
  22318. }
  22319. else {
  22320. cam._postProcesses = this._postProcesses.slice(0);
  22321. }
  22322. }
  22323. };
  22324. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22325. if (insertAt === void 0) { insertAt = null; }
  22326. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22327. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22328. return 0;
  22329. }
  22330. if (insertAt == null || insertAt < 0) {
  22331. this._postProcesses.push(postProcess);
  22332. }
  22333. else if (this._postProcesses[insertAt] === null) {
  22334. this._postProcesses[insertAt] = postProcess;
  22335. }
  22336. else {
  22337. this._postProcesses.splice(insertAt, 0, postProcess);
  22338. }
  22339. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22340. return this._postProcesses.indexOf(postProcess);
  22341. };
  22342. Camera.prototype.detachPostProcess = function (postProcess) {
  22343. var idx = this._postProcesses.indexOf(postProcess);
  22344. if (idx !== -1) {
  22345. this._postProcesses[idx] = null;
  22346. }
  22347. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22348. };
  22349. Camera.prototype.getWorldMatrix = function () {
  22350. if (this._isSynchronizedViewMatrix()) {
  22351. return this._worldMatrix;
  22352. }
  22353. // Getting the the view matrix will also compute the world matrix.
  22354. this.getViewMatrix();
  22355. return this._worldMatrix;
  22356. };
  22357. Camera.prototype._getViewMatrix = function () {
  22358. return BABYLON.Matrix.Identity();
  22359. };
  22360. Camera.prototype.getViewMatrix = function (force) {
  22361. if (!force && this._isSynchronizedViewMatrix()) {
  22362. return this._computedViewMatrix;
  22363. }
  22364. this.updateCache();
  22365. this._computedViewMatrix = this._getViewMatrix();
  22366. this._currentRenderId = this.getScene().getRenderId();
  22367. this._childRenderId = this._currentRenderId;
  22368. this._refreshFrustumPlanes = true;
  22369. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22370. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22371. }
  22372. this.onViewMatrixChangedObservable.notifyObservers(this);
  22373. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22374. return this._computedViewMatrix;
  22375. };
  22376. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22377. this._doNotComputeProjectionMatrix = true;
  22378. if (projection !== undefined) {
  22379. this._projectionMatrix = projection;
  22380. }
  22381. };
  22382. ;
  22383. Camera.prototype.unfreezeProjectionMatrix = function () {
  22384. this._doNotComputeProjectionMatrix = false;
  22385. };
  22386. ;
  22387. Camera.prototype.getProjectionMatrix = function (force) {
  22388. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22389. return this._projectionMatrix;
  22390. }
  22391. // Cache
  22392. this._cache.mode = this.mode;
  22393. this._cache.minZ = this.minZ;
  22394. this._cache.maxZ = this.maxZ;
  22395. // Matrix
  22396. this._refreshFrustumPlanes = true;
  22397. var engine = this.getEngine();
  22398. var scene = this.getScene();
  22399. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22400. this._cache.fov = this.fov;
  22401. this._cache.fovMode = this.fovMode;
  22402. this._cache.aspectRatio = engine.getAspectRatio(this);
  22403. if (this.minZ <= 0) {
  22404. this.minZ = 0.1;
  22405. }
  22406. if (scene.useRightHandedSystem) {
  22407. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22408. }
  22409. else {
  22410. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22411. }
  22412. }
  22413. else {
  22414. var halfWidth = engine.getRenderWidth() / 2.0;
  22415. var halfHeight = engine.getRenderHeight() / 2.0;
  22416. if (scene.useRightHandedSystem) {
  22417. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22418. }
  22419. else {
  22420. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22421. }
  22422. this._cache.orthoLeft = this.orthoLeft;
  22423. this._cache.orthoRight = this.orthoRight;
  22424. this._cache.orthoBottom = this.orthoBottom;
  22425. this._cache.orthoTop = this.orthoTop;
  22426. this._cache.renderWidth = engine.getRenderWidth();
  22427. this._cache.renderHeight = engine.getRenderHeight();
  22428. }
  22429. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22430. return this._projectionMatrix;
  22431. };
  22432. Camera.prototype.getTranformationMatrix = function () {
  22433. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22434. return this._transformMatrix;
  22435. };
  22436. Camera.prototype.updateFrustumPlanes = function () {
  22437. if (!this._refreshFrustumPlanes) {
  22438. return;
  22439. }
  22440. this.getTranformationMatrix();
  22441. if (!this._frustumPlanes) {
  22442. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22443. }
  22444. else {
  22445. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22446. }
  22447. this._refreshFrustumPlanes = false;
  22448. };
  22449. Camera.prototype.isInFrustum = function (target) {
  22450. this.updateFrustumPlanes();
  22451. return target.isInFrustum(this._frustumPlanes);
  22452. };
  22453. Camera.prototype.isCompletelyInFrustum = function (target) {
  22454. this.updateFrustumPlanes();
  22455. return target.isCompletelyInFrustum(this._frustumPlanes);
  22456. };
  22457. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22458. if (length === void 0) { length = 100; }
  22459. if (!transform) {
  22460. transform = this.getWorldMatrix();
  22461. }
  22462. if (!origin) {
  22463. origin = this.position;
  22464. }
  22465. var forward = new BABYLON.Vector3(0, 0, 1);
  22466. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22467. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22468. return new BABYLON.Ray(origin, direction, length);
  22469. };
  22470. /**
  22471. * Releases resources associated with this node.
  22472. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22473. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22474. */
  22475. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22476. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22477. // Observables
  22478. this.onViewMatrixChangedObservable.clear();
  22479. this.onProjectionMatrixChangedObservable.clear();
  22480. this.onAfterCheckInputsObservable.clear();
  22481. this.onRestoreStateObservable.clear();
  22482. // Inputs
  22483. if (this.inputs) {
  22484. this.inputs.clear();
  22485. }
  22486. // Animations
  22487. this.getScene().stopAnimation(this);
  22488. // Remove from scene
  22489. this.getScene().removeCamera(this);
  22490. while (this._rigCameras.length > 0) {
  22491. var camera = this._rigCameras.pop();
  22492. if (camera) {
  22493. camera.dispose();
  22494. }
  22495. }
  22496. // Postprocesses
  22497. if (this._rigPostProcess) {
  22498. this._rigPostProcess.dispose(this);
  22499. this._rigPostProcess = null;
  22500. this._postProcesses = [];
  22501. }
  22502. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22503. this._rigPostProcess = null;
  22504. this._postProcesses = [];
  22505. }
  22506. else {
  22507. var i = this._postProcesses.length;
  22508. while (--i >= 0) {
  22509. var postProcess = this._postProcesses[i];
  22510. if (postProcess) {
  22511. postProcess.dispose(this);
  22512. }
  22513. }
  22514. }
  22515. // Render targets
  22516. var i = this.customRenderTargets.length;
  22517. while (--i >= 0) {
  22518. this.customRenderTargets[i].dispose();
  22519. }
  22520. this.customRenderTargets = [];
  22521. // Active Meshes
  22522. this._activeMeshes.dispose();
  22523. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22524. };
  22525. Object.defineProperty(Camera.prototype, "leftCamera", {
  22526. // ---- Camera rigs section ----
  22527. get: function () {
  22528. if (this._rigCameras.length < 1) {
  22529. return null;
  22530. }
  22531. return this._rigCameras[0];
  22532. },
  22533. enumerable: true,
  22534. configurable: true
  22535. });
  22536. Object.defineProperty(Camera.prototype, "rightCamera", {
  22537. get: function () {
  22538. if (this._rigCameras.length < 2) {
  22539. return null;
  22540. }
  22541. return this._rigCameras[1];
  22542. },
  22543. enumerable: true,
  22544. configurable: true
  22545. });
  22546. Camera.prototype.getLeftTarget = function () {
  22547. if (this._rigCameras.length < 1) {
  22548. return null;
  22549. }
  22550. return this._rigCameras[0].getTarget();
  22551. };
  22552. Camera.prototype.getRightTarget = function () {
  22553. if (this._rigCameras.length < 2) {
  22554. return null;
  22555. }
  22556. return this._rigCameras[1].getTarget();
  22557. };
  22558. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22559. if (this.cameraRigMode === mode) {
  22560. return;
  22561. }
  22562. while (this._rigCameras.length > 0) {
  22563. var camera = this._rigCameras.pop();
  22564. if (camera) {
  22565. camera.dispose();
  22566. }
  22567. }
  22568. this.cameraRigMode = mode;
  22569. this._cameraRigParams = {};
  22570. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22571. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22572. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22573. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22574. // create the rig cameras, unless none
  22575. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22576. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22577. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22578. if (leftCamera && rightCamera) {
  22579. this._rigCameras.push(leftCamera);
  22580. this._rigCameras.push(rightCamera);
  22581. }
  22582. }
  22583. switch (this.cameraRigMode) {
  22584. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22585. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22586. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22587. break;
  22588. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22589. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22590. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22591. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22592. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22593. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22594. break;
  22595. case Camera.RIG_MODE_VR:
  22596. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22597. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22598. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22599. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22600. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22601. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22602. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22603. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22604. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22605. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22606. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22607. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22608. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22609. if (metrics.compensateDistortion) {
  22610. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22611. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22612. }
  22613. break;
  22614. case Camera.RIG_MODE_WEBVR:
  22615. if (rigParams.vrDisplay) {
  22616. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22617. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22618. //Left eye
  22619. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22620. this._rigCameras[0].setCameraRigParameter("left", true);
  22621. //leaving this for future reference
  22622. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22623. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22624. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22625. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22626. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22627. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22628. this._rigCameras[0].parent = this;
  22629. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22630. //Right eye
  22631. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22632. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22633. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22634. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22635. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22636. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22637. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22638. this._rigCameras[1].parent = this;
  22639. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22640. if (Camera.UseAlternateWebVRRendering) {
  22641. this._rigCameras[1]._skipRendering = true;
  22642. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22643. }
  22644. }
  22645. break;
  22646. }
  22647. this._cascadePostProcessesToRigCams();
  22648. this.update();
  22649. };
  22650. Camera.prototype._getVRProjectionMatrix = function () {
  22651. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22652. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22653. return this._projectionMatrix;
  22654. };
  22655. Camera.prototype._updateCameraRotationMatrix = function () {
  22656. //Here for WebVR
  22657. };
  22658. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  22659. //Here for WebVR
  22660. };
  22661. /**
  22662. * This function MUST be overwritten by the different WebVR cameras available.
  22663. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22664. */
  22665. Camera.prototype._getWebVRProjectionMatrix = function () {
  22666. return BABYLON.Matrix.Identity();
  22667. };
  22668. /**
  22669. * This function MUST be overwritten by the different WebVR cameras available.
  22670. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22671. */
  22672. Camera.prototype._getWebVRViewMatrix = function () {
  22673. return BABYLON.Matrix.Identity();
  22674. };
  22675. Camera.prototype.setCameraRigParameter = function (name, value) {
  22676. if (!this._cameraRigParams) {
  22677. this._cameraRigParams = {};
  22678. }
  22679. this._cameraRigParams[name] = value;
  22680. //provisionnally:
  22681. if (name === "interaxialDistance") {
  22682. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  22683. }
  22684. };
  22685. /**
  22686. * needs to be overridden by children so sub has required properties to be copied
  22687. */
  22688. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  22689. return null;
  22690. };
  22691. /**
  22692. * May need to be overridden by children
  22693. */
  22694. Camera.prototype._updateRigCameras = function () {
  22695. for (var i = 0; i < this._rigCameras.length; i++) {
  22696. this._rigCameras[i].minZ = this.minZ;
  22697. this._rigCameras[i].maxZ = this.maxZ;
  22698. this._rigCameras[i].fov = this.fov;
  22699. }
  22700. // only update viewport when ANAGLYPH
  22701. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  22702. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  22703. }
  22704. };
  22705. Camera.prototype._setupInputs = function () {
  22706. };
  22707. Camera.prototype.serialize = function () {
  22708. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22709. // Type
  22710. serializationObject.type = this.getClassName();
  22711. // Parent
  22712. if (this.parent) {
  22713. serializationObject.parentId = this.parent.id;
  22714. }
  22715. if (this.inputs) {
  22716. this.inputs.serialize(serializationObject);
  22717. }
  22718. // Animations
  22719. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22720. serializationObject.ranges = this.serializeAnimationRanges();
  22721. return serializationObject;
  22722. };
  22723. Camera.prototype.clone = function (name) {
  22724. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  22725. };
  22726. Camera.prototype.getDirection = function (localAxis) {
  22727. var result = BABYLON.Vector3.Zero();
  22728. this.getDirectionToRef(localAxis, result);
  22729. return result;
  22730. };
  22731. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  22732. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  22733. };
  22734. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  22735. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  22736. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  22737. switch (type) {
  22738. case "ArcRotateCamera":
  22739. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  22740. case "DeviceOrientationCamera":
  22741. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  22742. case "FollowCamera":
  22743. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  22744. case "ArcFollowCamera":
  22745. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  22746. case "GamepadCamera":
  22747. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22748. case "TouchCamera":
  22749. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  22750. case "VirtualJoysticksCamera":
  22751. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  22752. case "WebVRFreeCamera":
  22753. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22754. case "WebVRGamepadCamera":
  22755. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22756. case "VRDeviceOrientationFreeCamera":
  22757. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22758. case "VRDeviceOrientationGamepadCamera":
  22759. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22760. case "AnaglyphArcRotateCamera":
  22761. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22762. case "AnaglyphFreeCamera":
  22763. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22764. case "AnaglyphGamepadCamera":
  22765. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22766. case "AnaglyphUniversalCamera":
  22767. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22768. case "StereoscopicArcRotateCamera":
  22769. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22770. case "StereoscopicFreeCamera":
  22771. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22772. case "StereoscopicGamepadCamera":
  22773. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22774. case "StereoscopicUniversalCamera":
  22775. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22776. case "FreeCamera": // Forcing Universal here
  22777. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22778. default: // Universal Camera is the default value
  22779. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22780. }
  22781. };
  22782. Camera.prototype.computeWorldMatrix = function () {
  22783. return this.getWorldMatrix();
  22784. };
  22785. Camera.Parse = function (parsedCamera, scene) {
  22786. var type = parsedCamera.type;
  22787. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  22788. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  22789. // Parent
  22790. if (parsedCamera.parentId) {
  22791. camera._waitingParentId = parsedCamera.parentId;
  22792. }
  22793. //If camera has an input manager, let it parse inputs settings
  22794. if (camera.inputs) {
  22795. camera.inputs.parse(parsedCamera);
  22796. camera._setupInputs();
  22797. }
  22798. if (camera.setPosition) { // need to force position
  22799. camera.position.copyFromFloats(0, 0, 0);
  22800. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  22801. }
  22802. // Target
  22803. if (parsedCamera.target) {
  22804. if (camera.setTarget) {
  22805. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  22806. }
  22807. }
  22808. // Apply 3d rig, when found
  22809. if (parsedCamera.cameraRigMode) {
  22810. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  22811. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  22812. }
  22813. // Animations
  22814. if (parsedCamera.animations) {
  22815. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  22816. var parsedAnimation = parsedCamera.animations[animationIndex];
  22817. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22818. }
  22819. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  22820. }
  22821. if (parsedCamera.autoAnimate) {
  22822. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  22823. }
  22824. return camera;
  22825. };
  22826. // Statics
  22827. Camera._PERSPECTIVE_CAMERA = 0;
  22828. Camera._ORTHOGRAPHIC_CAMERA = 1;
  22829. Camera._FOVMODE_VERTICAL_FIXED = 0;
  22830. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  22831. Camera._RIG_MODE_NONE = 0;
  22832. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  22833. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  22834. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  22835. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  22836. Camera._RIG_MODE_VR = 20;
  22837. Camera._RIG_MODE_WEBVR = 21;
  22838. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  22839. Camera.UseAlternateWebVRRendering = false;
  22840. __decorate([
  22841. BABYLON.serializeAsVector3()
  22842. ], Camera.prototype, "position", void 0);
  22843. __decorate([
  22844. BABYLON.serializeAsVector3()
  22845. ], Camera.prototype, "upVector", void 0);
  22846. __decorate([
  22847. BABYLON.serialize()
  22848. ], Camera.prototype, "orthoLeft", void 0);
  22849. __decorate([
  22850. BABYLON.serialize()
  22851. ], Camera.prototype, "orthoRight", void 0);
  22852. __decorate([
  22853. BABYLON.serialize()
  22854. ], Camera.prototype, "orthoBottom", void 0);
  22855. __decorate([
  22856. BABYLON.serialize()
  22857. ], Camera.prototype, "orthoTop", void 0);
  22858. __decorate([
  22859. BABYLON.serialize()
  22860. ], Camera.prototype, "fov", void 0);
  22861. __decorate([
  22862. BABYLON.serialize()
  22863. ], Camera.prototype, "minZ", void 0);
  22864. __decorate([
  22865. BABYLON.serialize()
  22866. ], Camera.prototype, "maxZ", void 0);
  22867. __decorate([
  22868. BABYLON.serialize()
  22869. ], Camera.prototype, "inertia", void 0);
  22870. __decorate([
  22871. BABYLON.serialize()
  22872. ], Camera.prototype, "mode", void 0);
  22873. __decorate([
  22874. BABYLON.serialize()
  22875. ], Camera.prototype, "layerMask", void 0);
  22876. __decorate([
  22877. BABYLON.serialize()
  22878. ], Camera.prototype, "fovMode", void 0);
  22879. __decorate([
  22880. BABYLON.serialize()
  22881. ], Camera.prototype, "cameraRigMode", void 0);
  22882. __decorate([
  22883. BABYLON.serialize()
  22884. ], Camera.prototype, "interaxialDistance", void 0);
  22885. __decorate([
  22886. BABYLON.serialize()
  22887. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  22888. return Camera;
  22889. }(BABYLON.Node));
  22890. BABYLON.Camera = Camera;
  22891. })(BABYLON || (BABYLON = {}));
  22892. //# sourceMappingURL=babylon.camera.js.map
  22893. var BABYLON;
  22894. (function (BABYLON) {
  22895. var RenderingManager = /** @class */ (function () {
  22896. function RenderingManager(scene) {
  22897. this._renderingGroups = new Array();
  22898. this._autoClearDepthStencil = {};
  22899. this._customOpaqueSortCompareFn = {};
  22900. this._customAlphaTestSortCompareFn = {};
  22901. this._customTransparentSortCompareFn = {};
  22902. this._renderinGroupInfo = null;
  22903. this._scene = scene;
  22904. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  22905. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  22906. }
  22907. }
  22908. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  22909. if (depth === void 0) { depth = true; }
  22910. if (stencil === void 0) { stencil = true; }
  22911. if (this._depthStencilBufferAlreadyCleaned) {
  22912. return;
  22913. }
  22914. this._scene.getEngine().clear(null, false, depth, stencil);
  22915. this._depthStencilBufferAlreadyCleaned = true;
  22916. };
  22917. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  22918. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  22919. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  22920. var info = null;
  22921. if (observable) {
  22922. if (!this._renderinGroupInfo) {
  22923. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  22924. }
  22925. info = this._renderinGroupInfo;
  22926. info.scene = this._scene;
  22927. info.camera = this._scene.activeCamera;
  22928. }
  22929. // Dispatch sprites
  22930. if (renderSprites) {
  22931. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  22932. var manager = this._scene.spriteManagers[index];
  22933. this.dispatchSprites(manager);
  22934. }
  22935. }
  22936. // Render
  22937. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22938. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  22939. var renderingGroup = this._renderingGroups[index];
  22940. if (!renderingGroup && !observable)
  22941. continue;
  22942. var renderingGroupMask = 0;
  22943. // Fire PRECLEAR stage
  22944. if (observable && info) {
  22945. renderingGroupMask = Math.pow(2, index);
  22946. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  22947. info.renderingGroupId = index;
  22948. observable.notifyObservers(info, renderingGroupMask);
  22949. }
  22950. // Clear depth/stencil if needed
  22951. if (RenderingManager.AUTOCLEAR) {
  22952. var autoClear = this._autoClearDepthStencil[index];
  22953. if (autoClear && autoClear.autoClear) {
  22954. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  22955. }
  22956. }
  22957. if (observable && info) {
  22958. // Fire PREOPAQUE stage
  22959. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  22960. observable.notifyObservers(info, renderingGroupMask);
  22961. // Fire PRETRANSPARENT stage
  22962. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  22963. observable.notifyObservers(info, renderingGroupMask);
  22964. }
  22965. if (renderingGroup)
  22966. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  22967. // Fire POSTTRANSPARENT stage
  22968. if (observable && info) {
  22969. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  22970. observable.notifyObservers(info, renderingGroupMask);
  22971. }
  22972. }
  22973. };
  22974. RenderingManager.prototype.reset = function () {
  22975. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22976. var renderingGroup = this._renderingGroups[index];
  22977. if (renderingGroup) {
  22978. renderingGroup.prepare();
  22979. }
  22980. }
  22981. };
  22982. RenderingManager.prototype.dispose = function () {
  22983. this.freeRenderingGroups();
  22984. this._renderingGroups.length = 0;
  22985. };
  22986. /**
  22987. * Clear the info related to rendering groups preventing retention points during dispose.
  22988. */
  22989. RenderingManager.prototype.freeRenderingGroups = function () {
  22990. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  22991. var renderingGroup = this._renderingGroups[index];
  22992. if (renderingGroup) {
  22993. renderingGroup.dispose();
  22994. }
  22995. }
  22996. };
  22997. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  22998. if (this._renderingGroups[renderingGroupId] === undefined) {
  22999. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  23000. }
  23001. };
  23002. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  23003. var renderingGroupId = spriteManager.renderingGroupId || 0;
  23004. this._prepareRenderingGroup(renderingGroupId);
  23005. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  23006. };
  23007. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  23008. var renderingGroupId = particleSystem.renderingGroupId || 0;
  23009. this._prepareRenderingGroup(renderingGroupId);
  23010. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  23011. };
  23012. /**
  23013. * @param subMesh The submesh to dispatch
  23014. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23015. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23016. */
  23017. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  23018. if (mesh === undefined) {
  23019. mesh = subMesh.getMesh();
  23020. }
  23021. var renderingGroupId = mesh.renderingGroupId || 0;
  23022. this._prepareRenderingGroup(renderingGroupId);
  23023. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  23024. };
  23025. /**
  23026. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23027. * This allowed control for front to back rendering or reversly depending of the special needs.
  23028. *
  23029. * @param renderingGroupId The rendering group id corresponding to its index
  23030. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23031. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23032. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23033. */
  23034. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23035. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23036. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23037. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23038. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  23039. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  23040. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  23041. if (this._renderingGroups[renderingGroupId]) {
  23042. var group = this._renderingGroups[renderingGroupId];
  23043. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  23044. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  23045. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  23046. }
  23047. };
  23048. /**
  23049. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23050. *
  23051. * @param renderingGroupId The rendering group id corresponding to its index
  23052. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23053. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23054. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23055. */
  23056. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23057. if (depth === void 0) { depth = true; }
  23058. if (stencil === void 0) { stencil = true; }
  23059. this._autoClearDepthStencil[renderingGroupId] = {
  23060. autoClear: autoClearDepthStencil,
  23061. depth: depth,
  23062. stencil: stencil
  23063. };
  23064. };
  23065. /**
  23066. * The max id used for rendering groups (not included)
  23067. */
  23068. RenderingManager.MAX_RENDERINGGROUPS = 4;
  23069. /**
  23070. * The min id used for rendering groups (included)
  23071. */
  23072. RenderingManager.MIN_RENDERINGGROUPS = 0;
  23073. /**
  23074. * Used to globally prevent autoclearing scenes.
  23075. */
  23076. RenderingManager.AUTOCLEAR = true;
  23077. return RenderingManager;
  23078. }());
  23079. BABYLON.RenderingManager = RenderingManager;
  23080. })(BABYLON || (BABYLON = {}));
  23081. //# sourceMappingURL=babylon.renderingManager.js.map
  23082. var BABYLON;
  23083. (function (BABYLON) {
  23084. var RenderingGroup = /** @class */ (function () {
  23085. /**
  23086. * Creates a new rendering group.
  23087. * @param index The rendering group index
  23088. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  23089. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  23090. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23091. */
  23092. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23093. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23094. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23095. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23096. this.index = index;
  23097. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23098. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23099. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23100. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23101. this._particleSystems = new BABYLON.SmartArray(256);
  23102. this._spriteManagers = new BABYLON.SmartArray(256);
  23103. this._edgesRenderers = new BABYLON.SmartArray(16);
  23104. this._scene = scene;
  23105. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23106. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23107. this.transparentSortCompareFn = transparentSortCompareFn;
  23108. }
  23109. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23110. /**
  23111. * Set the opaque sort comparison function.
  23112. * If null the sub meshes will be render in the order they were created
  23113. */
  23114. set: function (value) {
  23115. this._opaqueSortCompareFn = value;
  23116. if (value) {
  23117. this._renderOpaque = this.renderOpaqueSorted;
  23118. }
  23119. else {
  23120. this._renderOpaque = RenderingGroup.renderUnsorted;
  23121. }
  23122. },
  23123. enumerable: true,
  23124. configurable: true
  23125. });
  23126. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23127. /**
  23128. * Set the alpha test sort comparison function.
  23129. * If null the sub meshes will be render in the order they were created
  23130. */
  23131. set: function (value) {
  23132. this._alphaTestSortCompareFn = value;
  23133. if (value) {
  23134. this._renderAlphaTest = this.renderAlphaTestSorted;
  23135. }
  23136. else {
  23137. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23138. }
  23139. },
  23140. enumerable: true,
  23141. configurable: true
  23142. });
  23143. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23144. /**
  23145. * Set the transparent sort comparison function.
  23146. * If null the sub meshes will be render in the order they were created
  23147. */
  23148. set: function (value) {
  23149. if (value) {
  23150. this._transparentSortCompareFn = value;
  23151. }
  23152. else {
  23153. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23154. }
  23155. this._renderTransparent = this.renderTransparentSorted;
  23156. },
  23157. enumerable: true,
  23158. configurable: true
  23159. });
  23160. /**
  23161. * Render all the sub meshes contained in the group.
  23162. * @param customRenderFunction Used to override the default render behaviour of the group.
  23163. * @returns true if rendered some submeshes.
  23164. */
  23165. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23166. if (customRenderFunction) {
  23167. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23168. return;
  23169. }
  23170. var engine = this._scene.getEngine();
  23171. // Depth only
  23172. if (this._depthOnlySubMeshes.length !== 0) {
  23173. engine.setColorWrite(false);
  23174. this._renderAlphaTest(this._depthOnlySubMeshes);
  23175. engine.setColorWrite(true);
  23176. }
  23177. // Opaque
  23178. if (this._opaqueSubMeshes.length !== 0) {
  23179. this._renderOpaque(this._opaqueSubMeshes);
  23180. }
  23181. // Alpha test
  23182. if (this._alphaTestSubMeshes.length !== 0) {
  23183. this._renderAlphaTest(this._alphaTestSubMeshes);
  23184. }
  23185. var stencilState = engine.getStencilBuffer();
  23186. engine.setStencilBuffer(false);
  23187. // Sprites
  23188. if (renderSprites) {
  23189. this._renderSprites();
  23190. }
  23191. // Particles
  23192. if (renderParticles) {
  23193. this._renderParticles(activeMeshes);
  23194. }
  23195. if (this.onBeforeTransparentRendering) {
  23196. this.onBeforeTransparentRendering();
  23197. }
  23198. // Transparent
  23199. if (this._transparentSubMeshes.length !== 0) {
  23200. this._renderTransparent(this._transparentSubMeshes);
  23201. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23202. }
  23203. // Set back stencil to false in case it changes before the edge renderer.
  23204. engine.setStencilBuffer(false);
  23205. // Edges
  23206. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23207. this._edgesRenderers.data[edgesRendererIndex].render();
  23208. }
  23209. // Restore Stencil state.
  23210. engine.setStencilBuffer(stencilState);
  23211. };
  23212. /**
  23213. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23214. * @param subMeshes The submeshes to render
  23215. */
  23216. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23217. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23218. };
  23219. /**
  23220. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23221. * @param subMeshes The submeshes to render
  23222. */
  23223. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23224. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23225. };
  23226. /**
  23227. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23228. * @param subMeshes The submeshes to render
  23229. */
  23230. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23231. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23232. };
  23233. /**
  23234. * Renders the submeshes in a specified order.
  23235. * @param subMeshes The submeshes to sort before render
  23236. * @param sortCompareFn The comparison function use to sort
  23237. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23238. * @param transparent Specifies to activate blending if true
  23239. */
  23240. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23241. var subIndex = 0;
  23242. var subMesh;
  23243. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23244. for (; subIndex < subMeshes.length; subIndex++) {
  23245. subMesh = subMeshes.data[subIndex];
  23246. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23247. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23248. }
  23249. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23250. if (sortCompareFn) {
  23251. sortedArray.sort(sortCompareFn);
  23252. }
  23253. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23254. subMesh = sortedArray[subIndex];
  23255. if (transparent) {
  23256. var material = subMesh.getMaterial();
  23257. if (material && material.needDepthPrePass) {
  23258. var engine = material.getScene().getEngine();
  23259. engine.setColorWrite(false);
  23260. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23261. subMesh.render(false);
  23262. engine.setColorWrite(true);
  23263. }
  23264. }
  23265. subMesh.render(transparent);
  23266. }
  23267. };
  23268. /**
  23269. * Renders the submeshes in the order they were dispatched (no sort applied).
  23270. * @param subMeshes The submeshes to render
  23271. */
  23272. RenderingGroup.renderUnsorted = function (subMeshes) {
  23273. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23274. var submesh = subMeshes.data[subIndex];
  23275. submesh.render(false);
  23276. }
  23277. };
  23278. /**
  23279. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23280. * are rendered back to front if in the same alpha index.
  23281. *
  23282. * @param a The first submesh
  23283. * @param b The second submesh
  23284. * @returns The result of the comparison
  23285. */
  23286. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23287. // Alpha index first
  23288. if (a._alphaIndex > b._alphaIndex) {
  23289. return 1;
  23290. }
  23291. if (a._alphaIndex < b._alphaIndex) {
  23292. return -1;
  23293. }
  23294. // Then distance to camera
  23295. return RenderingGroup.backToFrontSortCompare(a, b);
  23296. };
  23297. /**
  23298. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23299. * are rendered back to front.
  23300. *
  23301. * @param a The first submesh
  23302. * @param b The second submesh
  23303. * @returns The result of the comparison
  23304. */
  23305. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23306. // Then distance to camera
  23307. if (a._distanceToCamera < b._distanceToCamera) {
  23308. return 1;
  23309. }
  23310. if (a._distanceToCamera > b._distanceToCamera) {
  23311. return -1;
  23312. }
  23313. return 0;
  23314. };
  23315. /**
  23316. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23317. * are rendered front to back (prevent overdraw).
  23318. *
  23319. * @param a The first submesh
  23320. * @param b The second submesh
  23321. * @returns The result of the comparison
  23322. */
  23323. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23324. // Then distance to camera
  23325. if (a._distanceToCamera < b._distanceToCamera) {
  23326. return -1;
  23327. }
  23328. if (a._distanceToCamera > b._distanceToCamera) {
  23329. return 1;
  23330. }
  23331. return 0;
  23332. };
  23333. /**
  23334. * Resets the different lists of submeshes to prepare a new frame.
  23335. */
  23336. RenderingGroup.prototype.prepare = function () {
  23337. this._opaqueSubMeshes.reset();
  23338. this._transparentSubMeshes.reset();
  23339. this._alphaTestSubMeshes.reset();
  23340. this._depthOnlySubMeshes.reset();
  23341. this._particleSystems.reset();
  23342. this._spriteManagers.reset();
  23343. this._edgesRenderers.reset();
  23344. };
  23345. RenderingGroup.prototype.dispose = function () {
  23346. this._opaqueSubMeshes.dispose();
  23347. this._transparentSubMeshes.dispose();
  23348. this._alphaTestSubMeshes.dispose();
  23349. this._depthOnlySubMeshes.dispose();
  23350. this._particleSystems.dispose();
  23351. this._spriteManagers.dispose();
  23352. this._edgesRenderers.dispose();
  23353. };
  23354. /**
  23355. * Inserts the submesh in its correct queue depending on its material.
  23356. * @param subMesh The submesh to dispatch
  23357. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23358. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23359. */
  23360. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23361. // Get mesh and materials if not provided
  23362. if (mesh === undefined) {
  23363. mesh = subMesh.getMesh();
  23364. }
  23365. if (material === undefined) {
  23366. material = subMesh.getMaterial();
  23367. }
  23368. if (material === null || material === undefined) {
  23369. return;
  23370. }
  23371. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23372. this._transparentSubMeshes.push(subMesh);
  23373. }
  23374. else if (material.needAlphaTesting()) { // Alpha test
  23375. if (material.needDepthPrePass) {
  23376. this._depthOnlySubMeshes.push(subMesh);
  23377. }
  23378. this._alphaTestSubMeshes.push(subMesh);
  23379. }
  23380. else {
  23381. if (material.needDepthPrePass) {
  23382. this._depthOnlySubMeshes.push(subMesh);
  23383. }
  23384. this._opaqueSubMeshes.push(subMesh); // Opaque
  23385. }
  23386. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  23387. this._edgesRenderers.push(mesh._edgesRenderer);
  23388. }
  23389. };
  23390. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23391. this._spriteManagers.push(spriteManager);
  23392. };
  23393. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23394. this._particleSystems.push(particleSystem);
  23395. };
  23396. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23397. if (this._particleSystems.length === 0) {
  23398. return;
  23399. }
  23400. // Particles
  23401. var activeCamera = this._scene.activeCamera;
  23402. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23403. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23404. var particleSystem = this._particleSystems.data[particleIndex];
  23405. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23406. continue;
  23407. }
  23408. var emitter = particleSystem.emitter;
  23409. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23410. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23411. }
  23412. }
  23413. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23414. };
  23415. RenderingGroup.prototype._renderSprites = function () {
  23416. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23417. return;
  23418. }
  23419. // Sprites
  23420. var activeCamera = this._scene.activeCamera;
  23421. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23422. for (var id = 0; id < this._spriteManagers.length; id++) {
  23423. var spriteManager = this._spriteManagers.data[id];
  23424. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23425. spriteManager.render();
  23426. }
  23427. }
  23428. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23429. };
  23430. return RenderingGroup;
  23431. }());
  23432. BABYLON.RenderingGroup = RenderingGroup;
  23433. })(BABYLON || (BABYLON = {}));
  23434. //# sourceMappingURL=babylon.renderingGroup.js.map
  23435. var BABYLON;
  23436. (function (BABYLON) {
  23437. /** @hidden */
  23438. var ClickInfo = /** @class */ (function () {
  23439. function ClickInfo() {
  23440. this._singleClick = false;
  23441. this._doubleClick = false;
  23442. this._hasSwiped = false;
  23443. this._ignore = false;
  23444. }
  23445. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  23446. get: function () {
  23447. return this._singleClick;
  23448. },
  23449. set: function (b) {
  23450. this._singleClick = b;
  23451. },
  23452. enumerable: true,
  23453. configurable: true
  23454. });
  23455. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23456. get: function () {
  23457. return this._doubleClick;
  23458. },
  23459. set: function (b) {
  23460. this._doubleClick = b;
  23461. },
  23462. enumerable: true,
  23463. configurable: true
  23464. });
  23465. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23466. get: function () {
  23467. return this._hasSwiped;
  23468. },
  23469. set: function (b) {
  23470. this._hasSwiped = b;
  23471. },
  23472. enumerable: true,
  23473. configurable: true
  23474. });
  23475. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23476. get: function () {
  23477. return this._ignore;
  23478. },
  23479. set: function (b) {
  23480. this._ignore = b;
  23481. },
  23482. enumerable: true,
  23483. configurable: true
  23484. });
  23485. return ClickInfo;
  23486. }());
  23487. /**
  23488. * This class is used by the onRenderingGroupObservable
  23489. */
  23490. var RenderingGroupInfo = /** @class */ (function () {
  23491. function RenderingGroupInfo() {
  23492. }
  23493. /**
  23494. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  23495. * This stage will be fired no matter what
  23496. */
  23497. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  23498. /**
  23499. * Called before opaque object are rendered.
  23500. * This stage will be fired only if there's 3D Opaque content to render
  23501. */
  23502. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  23503. /**
  23504. * Called after the opaque objects are rendered and before the transparent ones
  23505. * This stage will be fired only if there's 3D transparent content to render
  23506. */
  23507. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  23508. /**
  23509. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  23510. * This stage will be fired no matter what
  23511. */
  23512. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  23513. return RenderingGroupInfo;
  23514. }());
  23515. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  23516. /**
  23517. * Represents a scene to be rendered by the engine.
  23518. * @see http://doc.babylonjs.com/features/scene
  23519. */
  23520. var Scene = /** @class */ (function () {
  23521. /**
  23522. * Creates a new Scene
  23523. * @param engine defines the engine to use to render this scene
  23524. */
  23525. function Scene(engine) {
  23526. // Members
  23527. /**
  23528. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  23529. */
  23530. this.autoClear = true;
  23531. /**
  23532. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  23533. */
  23534. this.autoClearDepthAndStencil = true;
  23535. /**
  23536. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  23537. */
  23538. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  23539. /**
  23540. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  23541. */
  23542. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23543. this._forceWireframe = false;
  23544. this._forcePointsCloud = false;
  23545. /**
  23546. * Gets or sets a boolean indicating if all bounding boxes must be rendered
  23547. */
  23548. this.forceShowBoundingBoxes = false;
  23549. /**
  23550. * Gets or sets a boolean indicating if animations are enabled
  23551. */
  23552. this.animationsEnabled = true;
  23553. this._animationPropertiesOverride = null;
  23554. /**
  23555. * Gets or sets a boolean indicating if a constant deltatime has to be used
  23556. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  23557. */
  23558. this.useConstantAnimationDeltaTime = false;
  23559. /**
  23560. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  23561. * Please note that it requires to run a ray cast through the scene on every frame
  23562. */
  23563. this.constantlyUpdateMeshUnderPointer = false;
  23564. /**
  23565. * Defines the HTML cursor to use when hovering over interactive elements
  23566. */
  23567. this.hoverCursor = "pointer";
  23568. /**
  23569. * Defines the HTML default cursor to use (empty by default)
  23570. */
  23571. this.defaultCursor = "";
  23572. /**
  23573. * This is used to call preventDefault() on pointer down
  23574. * in order to block unwanted artifacts like system double clicks
  23575. */
  23576. this.preventDefaultOnPointerDown = true;
  23577. // Metadata
  23578. /**
  23579. * Gets or sets user defined metadata
  23580. */
  23581. this.metadata = null;
  23582. /**
  23583. * Use this array to add regular expressions used to disable offline support for specific urls
  23584. */
  23585. this.disableOfflineSupportExceptionRules = new Array();
  23586. /**
  23587. * An event triggered when the scene is disposed.
  23588. */
  23589. this.onDisposeObservable = new BABYLON.Observable();
  23590. this._onDisposeObserver = null;
  23591. /**
  23592. * An event triggered before rendering the scene (right after animations and physics)
  23593. */
  23594. this.onBeforeRenderObservable = new BABYLON.Observable();
  23595. this._onBeforeRenderObserver = null;
  23596. /**
  23597. * An event triggered after rendering the scene
  23598. */
  23599. this.onAfterRenderObservable = new BABYLON.Observable();
  23600. this._onAfterRenderObserver = null;
  23601. /**
  23602. * An event triggered before animating the scene
  23603. */
  23604. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  23605. /**
  23606. * An event triggered after animations processing
  23607. */
  23608. this.onAfterAnimationsObservable = new BABYLON.Observable();
  23609. /**
  23610. * An event triggered before draw calls are ready to be sent
  23611. */
  23612. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  23613. /**
  23614. * An event triggered after draw calls have been sent
  23615. */
  23616. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  23617. /**
  23618. * An event triggered when physic simulation is about to be run
  23619. */
  23620. this.onBeforePhysicsObservable = new BABYLON.Observable();
  23621. /**
  23622. * An event triggered when physic simulation has been done
  23623. */
  23624. this.onAfterPhysicsObservable = new BABYLON.Observable();
  23625. /**
  23626. * An event triggered when the scene is ready
  23627. */
  23628. this.onReadyObservable = new BABYLON.Observable();
  23629. /**
  23630. * An event triggered before rendering a camera
  23631. */
  23632. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  23633. this._onBeforeCameraRenderObserver = null;
  23634. /**
  23635. * An event triggered after rendering a camera
  23636. */
  23637. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  23638. this._onAfterCameraRenderObserver = null;
  23639. /**
  23640. * An event triggered when active meshes evaluation is about to start
  23641. */
  23642. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23643. /**
  23644. * An event triggered when active meshes evaluation is done
  23645. */
  23646. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23647. /**
  23648. * An event triggered when particles rendering is about to start
  23649. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23650. */
  23651. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  23652. /**
  23653. * An event triggered when particles rendering is done
  23654. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23655. */
  23656. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  23657. /**
  23658. * An event triggered when sprites rendering is about to start
  23659. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23660. */
  23661. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  23662. /**
  23663. * An event triggered when sprites rendering is done
  23664. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23665. */
  23666. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  23667. /**
  23668. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  23669. */
  23670. this.onDataLoadedObservable = new BABYLON.Observable();
  23671. /**
  23672. * An event triggered when a camera is created
  23673. */
  23674. this.onNewCameraAddedObservable = new BABYLON.Observable();
  23675. /**
  23676. * An event triggered when a camera is removed
  23677. */
  23678. this.onCameraRemovedObservable = new BABYLON.Observable();
  23679. /**
  23680. * An event triggered when a light is created
  23681. */
  23682. this.onNewLightAddedObservable = new BABYLON.Observable();
  23683. /**
  23684. * An event triggered when a light is removed
  23685. */
  23686. this.onLightRemovedObservable = new BABYLON.Observable();
  23687. /**
  23688. * An event triggered when a geometry is created
  23689. */
  23690. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  23691. /**
  23692. * An event triggered when a geometry is removed
  23693. */
  23694. this.onGeometryRemovedObservable = new BABYLON.Observable();
  23695. /**
  23696. * An event triggered when a transform node is created
  23697. */
  23698. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  23699. /**
  23700. * An event triggered when a transform node is removed
  23701. */
  23702. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  23703. /**
  23704. * An event triggered when a mesh is created
  23705. */
  23706. this.onNewMeshAddedObservable = new BABYLON.Observable();
  23707. /**
  23708. * An event triggered when a mesh is removed
  23709. */
  23710. this.onMeshRemovedObservable = new BABYLON.Observable();
  23711. /**
  23712. * An event triggered when render targets are about to be rendered
  23713. * Can happen multiple times per frame.
  23714. */
  23715. this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  23716. /**
  23717. * An event triggered when render targets were rendered.
  23718. * Can happen multiple times per frame.
  23719. */
  23720. this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  23721. /**
  23722. * An event triggered before calculating deterministic simulation step
  23723. */
  23724. this.onBeforeStepObservable = new BABYLON.Observable();
  23725. /**
  23726. * An event triggered after calculating deterministic simulation step
  23727. */
  23728. this.onAfterStepObservable = new BABYLON.Observable();
  23729. /**
  23730. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  23731. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  23732. * 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)
  23733. */
  23734. this.onRenderingGroupObservable = new BABYLON.Observable();
  23735. // Animations
  23736. /**
  23737. * Gets a list of Animations associated with the scene
  23738. */
  23739. this.animations = [];
  23740. this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  23741. /**
  23742. * 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).
  23743. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  23744. */
  23745. this.onPrePointerObservable = new BABYLON.Observable();
  23746. /**
  23747. * Observable event triggered each time an input event is received from the rendering canvas
  23748. */
  23749. this.onPointerObservable = new BABYLON.Observable();
  23750. this._meshPickProceed = false;
  23751. this._currentPickResult = null;
  23752. this._previousPickResult = null;
  23753. this._totalPointersPressed = 0;
  23754. this._doubleClickOccured = false;
  23755. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  23756. this.cameraToUseForPointers = null;
  23757. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  23758. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  23759. this._startingPointerTime = 0;
  23760. this._previousStartingPointerTime = 0;
  23761. this._pointerCaptures = {};
  23762. // Deterministic lockstep
  23763. this._timeAccumulator = 0;
  23764. this._currentStepId = 0;
  23765. this._currentInternalStep = 0;
  23766. // Keyboard
  23767. /**
  23768. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  23769. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  23770. */
  23771. this.onPreKeyboardObservable = new BABYLON.Observable();
  23772. /**
  23773. * Observable event triggered each time an keyboard event is received from the hosting window
  23774. */
  23775. this.onKeyboardObservable = new BABYLON.Observable();
  23776. // Coordinates system
  23777. this._useRightHandedSystem = false;
  23778. // Fog
  23779. this._fogEnabled = true;
  23780. this._fogMode = Scene.FOGMODE_NONE;
  23781. /**
  23782. * Gets or sets the fog color to use
  23783. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23784. */
  23785. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  23786. /**
  23787. * Gets or sets the fog density to use
  23788. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23789. */
  23790. this.fogDensity = 0.1;
  23791. /**
  23792. * Gets or sets the fog start distance to use
  23793. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23794. */
  23795. this.fogStart = 0;
  23796. /**
  23797. * Gets or sets the fog end distance to use
  23798. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23799. */
  23800. this.fogEnd = 1000.0;
  23801. // Lights
  23802. this._shadowsEnabled = true;
  23803. this._lightsEnabled = true;
  23804. /**
  23805. * All of the lights added to this scene
  23806. * @see http://doc.babylonjs.com/babylon101/lights
  23807. */
  23808. this.lights = new Array();
  23809. // Cameras
  23810. /** All of the cameras added to this scene.
  23811. * @see http://doc.babylonjs.com/babylon101/cameras
  23812. */
  23813. this.cameras = new Array();
  23814. /** All of the active cameras added to this scene. */
  23815. this.activeCameras = new Array();
  23816. // Meshes
  23817. /**
  23818. * All of the tranform nodes added to this scene
  23819. * @see http://doc.babylonjs.com/how_to/transformnode
  23820. */
  23821. this.transformNodes = new Array();
  23822. /**
  23823. * All of the (abstract) meshes added to this scene
  23824. */
  23825. this.meshes = new Array();
  23826. /**
  23827. * All of the animation groups added to this scene
  23828. * @see http://doc.babylonjs.com/how_to/group
  23829. */
  23830. this.animationGroups = new Array();
  23831. // Geometries
  23832. this._geometries = new Array();
  23833. /**
  23834. * All of the materials added to this scene
  23835. * @see http://doc.babylonjs.com/babylon101/materials
  23836. */
  23837. this.materials = new Array();
  23838. /**
  23839. * All of the multi-materials added to this scene
  23840. * @see http://doc.babylonjs.com/how_to/multi_materials
  23841. */
  23842. this.multiMaterials = new Array();
  23843. // Textures
  23844. this._texturesEnabled = true;
  23845. /**
  23846. * All of the textures added to this scene
  23847. */
  23848. this.textures = new Array();
  23849. // Particles
  23850. /**
  23851. * Gets or sets a boolean indicating if particles are enabled on this scene
  23852. */
  23853. this.particlesEnabled = true;
  23854. /**
  23855. * All of the particle systems added to this scene
  23856. * @see http://doc.babylonjs.com/babylon101/particles
  23857. */
  23858. this.particleSystems = new Array();
  23859. // Sprites
  23860. /**
  23861. * Gets or sets a boolean indicating if sprites are enabled on this scene
  23862. */
  23863. this.spritesEnabled = true;
  23864. /**
  23865. * All of the sprite managers added to this scene
  23866. * @see http://doc.babylonjs.com/babylon101/sprites
  23867. */
  23868. this.spriteManagers = new Array();
  23869. /**
  23870. * The list of layers (background and foreground) of the scene
  23871. */
  23872. this.layers = new Array();
  23873. /**
  23874. * The list of effect layers (highlights/glow) added to the scene
  23875. * @see http://doc.babylonjs.com/how_to/highlight_layer
  23876. * @see http://doc.babylonjs.com/how_to/glow_layer
  23877. */
  23878. this.effectLayers = new Array();
  23879. // Skeletons
  23880. this._skeletonsEnabled = true;
  23881. /**
  23882. * The list of skeletons added to the scene
  23883. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  23884. */
  23885. this.skeletons = new Array();
  23886. // Morph targets
  23887. /**
  23888. * The list of morph target managers added to the scene
  23889. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  23890. */
  23891. this.morphTargetManagers = new Array();
  23892. // Lens flares
  23893. /**
  23894. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  23895. */
  23896. this.lensFlaresEnabled = true;
  23897. /**
  23898. * The list of lens flare system added to the scene
  23899. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  23900. */
  23901. this.lensFlareSystems = new Array();
  23902. // Collisions
  23903. /**
  23904. * Gets or sets a boolean indicating if collisions are enabled on this scene
  23905. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  23906. */
  23907. this.collisionsEnabled = true;
  23908. /**
  23909. * Defines the gravity applied to this scene (used only for collisions)
  23910. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  23911. */
  23912. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  23913. // Postprocesses
  23914. /**
  23915. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  23916. */
  23917. this.postProcessesEnabled = true;
  23918. /**
  23919. * The list of postprocesses added to the scene
  23920. */
  23921. this.postProcesses = new Array();
  23922. // Customs render targets
  23923. /**
  23924. * Gets or sets a boolean indicating if render targets are enabled on this scene
  23925. */
  23926. this.renderTargetsEnabled = true;
  23927. /**
  23928. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  23929. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  23930. */
  23931. this.dumpNextRenderTargets = false;
  23932. /**
  23933. * The list of user defined render targets added to the scene
  23934. */
  23935. this.customRenderTargets = new Array();
  23936. /**
  23937. * Gets the list of meshes imported to the scene through SceneLoader
  23938. */
  23939. this.importedMeshesFiles = new Array();
  23940. // Probes
  23941. /**
  23942. * Gets or sets a boolean indicating if probes are enabled on this scene
  23943. */
  23944. this.probesEnabled = true;
  23945. /**
  23946. * The list of reflection probes added to the scene
  23947. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  23948. */
  23949. this.reflectionProbes = new Array();
  23950. /** @hidden */
  23951. this._actionManagers = new Array();
  23952. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  23953. // Procedural textures
  23954. /**
  23955. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  23956. */
  23957. this.proceduralTexturesEnabled = true;
  23958. /**
  23959. * The list of procedural textures added to the scene
  23960. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  23961. */
  23962. this.proceduralTextures = new Array();
  23963. /**
  23964. * The list of sound tracks added to the scene
  23965. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  23966. */
  23967. this.soundTracks = new Array();
  23968. this._audioEnabled = true;
  23969. this._headphone = false;
  23970. // Performance counters
  23971. this._totalVertices = new BABYLON.PerfCounter();
  23972. /** @hidden */
  23973. this._activeIndices = new BABYLON.PerfCounter();
  23974. /** @hidden */
  23975. this._activeParticles = new BABYLON.PerfCounter();
  23976. /** @hidden */
  23977. this._activeBones = new BABYLON.PerfCounter();
  23978. this._animationTime = 0;
  23979. /**
  23980. * Gets or sets a general scale for animation speed
  23981. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  23982. */
  23983. this.animationTimeScale = 1;
  23984. this._renderId = 0;
  23985. this._executeWhenReadyTimeoutId = -1;
  23986. this._intermediateRendering = false;
  23987. this._viewUpdateFlag = -1;
  23988. this._projectionUpdateFlag = -1;
  23989. this._alternateViewUpdateFlag = -1;
  23990. this._alternateProjectionUpdateFlag = -1;
  23991. /** @hidden */
  23992. this._toBeDisposed = new BABYLON.SmartArray(256);
  23993. this._activeRequests = new Array();
  23994. this._pendingData = new Array();
  23995. this._isDisposed = false;
  23996. /**
  23997. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  23998. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  23999. */
  24000. this.dispatchAllSubMeshesOfActiveMeshes = false;
  24001. this._activeMeshes = new BABYLON.SmartArray(256);
  24002. this._processedMaterials = new BABYLON.SmartArray(256);
  24003. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24004. /** @hidden */
  24005. this._activeParticleSystems = new BABYLON.SmartArray(256);
  24006. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24007. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24008. /** @hidden */
  24009. this._activeAnimatables = new Array();
  24010. this._transformMatrix = BABYLON.Matrix.Zero();
  24011. this._useAlternateCameraConfiguration = false;
  24012. this._alternateRendering = false;
  24013. /**
  24014. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24015. * This is useful if there are more lights that the maximum simulteanous authorized
  24016. */
  24017. this.requireLightSorting = false;
  24018. this._depthRenderer = {};
  24019. this._activeMeshesFrozen = false;
  24020. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24021. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24022. this._engine.scenes.push(this);
  24023. this._uid = null;
  24024. this._renderingManager = new BABYLON.RenderingManager(this);
  24025. this.postProcessManager = new BABYLON.PostProcessManager(this);
  24026. if (BABYLON.OutlineRenderer) {
  24027. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  24028. }
  24029. if (BABYLON.Tools.IsWindowObjectExist()) {
  24030. this.attachControl();
  24031. }
  24032. //simplification queue
  24033. if (BABYLON.SimplificationQueue) {
  24034. this.simplificationQueue = new BABYLON.SimplificationQueue();
  24035. }
  24036. //collision coordinator initialization. For now legacy per default.
  24037. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24038. // Uniform Buffer
  24039. this._createUbo();
  24040. // Default Image processing definition.
  24041. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24042. }
  24043. Object.defineProperty(Scene, "FOGMODE_NONE", {
  24044. /** The fog is deactivated */
  24045. get: function () {
  24046. return Scene._FOGMODE_NONE;
  24047. },
  24048. enumerable: true,
  24049. configurable: true
  24050. });
  24051. Object.defineProperty(Scene, "FOGMODE_EXP", {
  24052. /** The fog density is following an exponential function */
  24053. get: function () {
  24054. return Scene._FOGMODE_EXP;
  24055. },
  24056. enumerable: true,
  24057. configurable: true
  24058. });
  24059. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  24060. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  24061. get: function () {
  24062. return Scene._FOGMODE_EXP2;
  24063. },
  24064. enumerable: true,
  24065. configurable: true
  24066. });
  24067. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  24068. /** The fog density is following a linear function. */
  24069. get: function () {
  24070. return Scene._FOGMODE_LINEAR;
  24071. },
  24072. enumerable: true,
  24073. configurable: true
  24074. });
  24075. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24076. /**
  24077. * Texture used in all pbr material as the reflection texture.
  24078. * As in the majority of the scene they are the same (exception for multi room and so on),
  24079. * this is easier to reference from here than from all the materials.
  24080. */
  24081. get: function () {
  24082. return this._environmentTexture;
  24083. },
  24084. /**
  24085. * Texture used in all pbr material as the reflection texture.
  24086. * As in the majority of the scene they are the same (exception for multi room and so on),
  24087. * this is easier to set here than in all the materials.
  24088. */
  24089. set: function (value) {
  24090. if (this._environmentTexture === value) {
  24091. return;
  24092. }
  24093. this._environmentTexture = value;
  24094. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24095. },
  24096. enumerable: true,
  24097. configurable: true
  24098. });
  24099. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24100. /**
  24101. * Default image processing configuration used either in the rendering
  24102. * Forward main pass or through the imageProcessingPostProcess if present.
  24103. * As in the majority of the scene they are the same (exception for multi camera),
  24104. * this is easier to reference from here than from all the materials and post process.
  24105. *
  24106. * No setter as we it is a shared configuration, you can set the values instead.
  24107. */
  24108. get: function () {
  24109. return this._imageProcessingConfiguration;
  24110. },
  24111. enumerable: true,
  24112. configurable: true
  24113. });
  24114. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24115. get: function () {
  24116. return this._forceWireframe;
  24117. },
  24118. /**
  24119. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24120. */
  24121. set: function (value) {
  24122. if (this._forceWireframe === value) {
  24123. return;
  24124. }
  24125. this._forceWireframe = value;
  24126. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24127. },
  24128. enumerable: true,
  24129. configurable: true
  24130. });
  24131. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24132. get: function () {
  24133. return this._forcePointsCloud;
  24134. },
  24135. /**
  24136. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24137. */
  24138. set: function (value) {
  24139. if (this._forcePointsCloud === value) {
  24140. return;
  24141. }
  24142. this._forcePointsCloud = value;
  24143. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24144. },
  24145. enumerable: true,
  24146. configurable: true
  24147. });
  24148. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24149. /**
  24150. * Gets or sets the animation properties override
  24151. */
  24152. get: function () {
  24153. return this._animationPropertiesOverride;
  24154. },
  24155. set: function (value) {
  24156. this._animationPropertiesOverride = value;
  24157. },
  24158. enumerable: true,
  24159. configurable: true
  24160. });
  24161. Object.defineProperty(Scene.prototype, "onDispose", {
  24162. /** Sets a function to be executed when this scene is disposed. */
  24163. set: function (callback) {
  24164. if (this._onDisposeObserver) {
  24165. this.onDisposeObservable.remove(this._onDisposeObserver);
  24166. }
  24167. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24168. },
  24169. enumerable: true,
  24170. configurable: true
  24171. });
  24172. Object.defineProperty(Scene.prototype, "beforeRender", {
  24173. /** Sets a function to be executed before rendering this scene */
  24174. set: function (callback) {
  24175. if (this._onBeforeRenderObserver) {
  24176. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24177. }
  24178. if (callback) {
  24179. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24180. }
  24181. },
  24182. enumerable: true,
  24183. configurable: true
  24184. });
  24185. Object.defineProperty(Scene.prototype, "afterRender", {
  24186. /** Sets a function to be executed after rendering this scene */
  24187. set: function (callback) {
  24188. if (this._onAfterRenderObserver) {
  24189. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24190. }
  24191. if (callback) {
  24192. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24193. }
  24194. },
  24195. enumerable: true,
  24196. configurable: true
  24197. });
  24198. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24199. /** Sets a function to be executed before rendering a camera*/
  24200. set: function (callback) {
  24201. if (this._onBeforeCameraRenderObserver) {
  24202. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24203. }
  24204. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24205. },
  24206. enumerable: true,
  24207. configurable: true
  24208. });
  24209. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24210. /** Sets a function to be executed after rendering a camera*/
  24211. set: function (callback) {
  24212. if (this._onAfterCameraRenderObserver) {
  24213. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24214. }
  24215. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24216. },
  24217. enumerable: true,
  24218. configurable: true
  24219. });
  24220. Object.defineProperty(Scene.prototype, "gamepadManager", {
  24221. /**
  24222. * Gets the gamepad manager associated with the scene
  24223. * @see http://doc.babylonjs.com/how_to/how_to_use_gamepads
  24224. */
  24225. get: function () {
  24226. if (!this._gamepadManager) {
  24227. this._gamepadManager = new BABYLON.GamepadManager(this);
  24228. }
  24229. return this._gamepadManager;
  24230. },
  24231. enumerable: true,
  24232. configurable: true
  24233. });
  24234. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24235. /**
  24236. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24237. */
  24238. get: function () {
  24239. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24240. },
  24241. enumerable: true,
  24242. configurable: true
  24243. });
  24244. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24245. get: function () {
  24246. return this._useRightHandedSystem;
  24247. },
  24248. /**
  24249. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24250. */
  24251. set: function (value) {
  24252. if (this._useRightHandedSystem === value) {
  24253. return;
  24254. }
  24255. this._useRightHandedSystem = value;
  24256. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24257. },
  24258. enumerable: true,
  24259. configurable: true
  24260. });
  24261. /**
  24262. * Sets the step Id used by deterministic lock step
  24263. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24264. * @param newStepId defines the step Id
  24265. */
  24266. Scene.prototype.setStepId = function (newStepId) {
  24267. this._currentStepId = newStepId;
  24268. };
  24269. ;
  24270. /**
  24271. * Gets the step Id used by deterministic lock step
  24272. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24273. * @returns the step Id
  24274. */
  24275. Scene.prototype.getStepId = function () {
  24276. return this._currentStepId;
  24277. };
  24278. ;
  24279. /**
  24280. * Gets the internal step used by deterministic lock step
  24281. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24282. * @returns the internal step
  24283. */
  24284. Scene.prototype.getInternalStep = function () {
  24285. return this._currentInternalStep;
  24286. };
  24287. ;
  24288. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24289. get: function () {
  24290. return this._fogEnabled;
  24291. },
  24292. /**
  24293. * Gets or sets a boolean indicating if fog is enabled on this scene
  24294. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24295. */
  24296. set: function (value) {
  24297. if (this._fogEnabled === value) {
  24298. return;
  24299. }
  24300. this._fogEnabled = value;
  24301. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24302. },
  24303. enumerable: true,
  24304. configurable: true
  24305. });
  24306. Object.defineProperty(Scene.prototype, "fogMode", {
  24307. get: function () {
  24308. return this._fogMode;
  24309. },
  24310. /**
  24311. * Gets or sets the fog mode to use
  24312. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24313. */
  24314. set: function (value) {
  24315. if (this._fogMode === value) {
  24316. return;
  24317. }
  24318. this._fogMode = value;
  24319. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24320. },
  24321. enumerable: true,
  24322. configurable: true
  24323. });
  24324. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24325. get: function () {
  24326. return this._shadowsEnabled;
  24327. },
  24328. /**
  24329. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24330. */
  24331. set: function (value) {
  24332. if (this._shadowsEnabled === value) {
  24333. return;
  24334. }
  24335. this._shadowsEnabled = value;
  24336. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24337. },
  24338. enumerable: true,
  24339. configurable: true
  24340. });
  24341. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24342. get: function () {
  24343. return this._lightsEnabled;
  24344. },
  24345. /**
  24346. * Gets or sets a boolean indicating if lights are enabled on this scene
  24347. */
  24348. set: function (value) {
  24349. if (this._lightsEnabled === value) {
  24350. return;
  24351. }
  24352. this._lightsEnabled = value;
  24353. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24354. },
  24355. enumerable: true,
  24356. configurable: true
  24357. });
  24358. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24359. /** The default material used on meshes when no material is affected */
  24360. get: function () {
  24361. if (!this._defaultMaterial) {
  24362. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24363. }
  24364. return this._defaultMaterial;
  24365. },
  24366. /** The default material used on meshes when no material is affected */
  24367. set: function (value) {
  24368. this._defaultMaterial = value;
  24369. },
  24370. enumerable: true,
  24371. configurable: true
  24372. });
  24373. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24374. get: function () {
  24375. return this._texturesEnabled;
  24376. },
  24377. /**
  24378. * Gets or sets a boolean indicating if textures are enabled on this scene
  24379. */
  24380. set: function (value) {
  24381. if (this._texturesEnabled === value) {
  24382. return;
  24383. }
  24384. this._texturesEnabled = value;
  24385. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24386. },
  24387. enumerable: true,
  24388. configurable: true
  24389. });
  24390. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24391. get: function () {
  24392. return this._skeletonsEnabled;
  24393. },
  24394. /**
  24395. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24396. */
  24397. set: function (value) {
  24398. if (this._skeletonsEnabled === value) {
  24399. return;
  24400. }
  24401. this._skeletonsEnabled = value;
  24402. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24403. },
  24404. enumerable: true,
  24405. configurable: true
  24406. });
  24407. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  24408. /**
  24409. * Gets the postprocess render pipeline manager
  24410. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  24411. * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  24412. */
  24413. get: function () {
  24414. if (!this._postProcessRenderPipelineManager) {
  24415. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  24416. }
  24417. return this._postProcessRenderPipelineManager;
  24418. },
  24419. enumerable: true,
  24420. configurable: true
  24421. });
  24422. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  24423. /**
  24424. * Gets the main soundtrack associated with the scene
  24425. */
  24426. get: function () {
  24427. if (!this._mainSoundTrack) {
  24428. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  24429. }
  24430. return this._mainSoundTrack;
  24431. },
  24432. enumerable: true,
  24433. configurable: true
  24434. });
  24435. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24436. /** @hidden */
  24437. get: function () {
  24438. return this._alternateRendering;
  24439. },
  24440. enumerable: true,
  24441. configurable: true
  24442. });
  24443. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24444. /**
  24445. * Gets the list of frustum planes (built from the active camera)
  24446. */
  24447. get: function () {
  24448. return this._frustumPlanes;
  24449. },
  24450. enumerable: true,
  24451. configurable: true
  24452. });
  24453. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  24454. /**
  24455. * Gets the current geometry buffer associated to the scene.
  24456. */
  24457. get: function () {
  24458. return this._geometryBufferRenderer;
  24459. },
  24460. /**
  24461. * Sets the current geometry buffer for the scene.
  24462. */
  24463. set: function (geometryBufferRenderer) {
  24464. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  24465. this._geometryBufferRenderer = geometryBufferRenderer;
  24466. }
  24467. },
  24468. enumerable: true,
  24469. configurable: true
  24470. });
  24471. Object.defineProperty(Scene.prototype, "debugLayer", {
  24472. /**
  24473. * Gets the debug layer associated with the scene
  24474. * @see http://doc.babylonjs.com/features/playground_debuglayer
  24475. */
  24476. get: function () {
  24477. if (!this._debugLayer) {
  24478. this._debugLayer = new BABYLON.DebugLayer(this);
  24479. }
  24480. return this._debugLayer;
  24481. },
  24482. enumerable: true,
  24483. configurable: true
  24484. });
  24485. Object.defineProperty(Scene.prototype, "workerCollisions", {
  24486. /**
  24487. * Gets a boolean indicating if collisions are processed on a web worker
  24488. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  24489. */
  24490. get: function () {
  24491. return this._workerCollisions;
  24492. },
  24493. set: function (enabled) {
  24494. if (!BABYLON.CollisionCoordinatorLegacy) {
  24495. return;
  24496. }
  24497. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  24498. this._workerCollisions = enabled;
  24499. if (this.collisionCoordinator) {
  24500. this.collisionCoordinator.destroy();
  24501. }
  24502. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  24503. this.collisionCoordinator.init(this);
  24504. },
  24505. enumerable: true,
  24506. configurable: true
  24507. });
  24508. Object.defineProperty(Scene.prototype, "selectionOctree", {
  24509. /**
  24510. * Gets the octree used to boost mesh selection (picking)
  24511. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  24512. */
  24513. get: function () {
  24514. return this._selectionOctree;
  24515. },
  24516. enumerable: true,
  24517. configurable: true
  24518. });
  24519. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  24520. /**
  24521. * Gets the mesh that is currently under the pointer
  24522. */
  24523. get: function () {
  24524. return this._pointerOverMesh;
  24525. },
  24526. enumerable: true,
  24527. configurable: true
  24528. });
  24529. Object.defineProperty(Scene.prototype, "pointerX", {
  24530. /**
  24531. * Gets the current on-screen X position of the pointer
  24532. */
  24533. get: function () {
  24534. return this._pointerX;
  24535. },
  24536. enumerable: true,
  24537. configurable: true
  24538. });
  24539. Object.defineProperty(Scene.prototype, "pointerY", {
  24540. /**
  24541. * Gets the current on-screen Y position of the pointer
  24542. */
  24543. get: function () {
  24544. return this._pointerY;
  24545. },
  24546. enumerable: true,
  24547. configurable: true
  24548. });
  24549. /**
  24550. * Gets the cached material (ie. the latest rendered one)
  24551. * @returns the cached material
  24552. */
  24553. Scene.prototype.getCachedMaterial = function () {
  24554. return this._cachedMaterial;
  24555. };
  24556. /**
  24557. * Gets the cached effect (ie. the latest rendered one)
  24558. * @returns the cached effect
  24559. */
  24560. Scene.prototype.getCachedEffect = function () {
  24561. return this._cachedEffect;
  24562. };
  24563. /**
  24564. * Gets the cached visibility state (ie. the latest rendered one)
  24565. * @returns the cached visibility state
  24566. */
  24567. Scene.prototype.getCachedVisibility = function () {
  24568. return this._cachedVisibility;
  24569. };
  24570. /**
  24571. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  24572. * @param material defines the current material
  24573. * @param effect defines the current effect
  24574. * @param visibility defines the current visibility state
  24575. * @returns true if one parameter is not cached
  24576. */
  24577. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  24578. if (visibility === void 0) { visibility = 1; }
  24579. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  24580. };
  24581. /**
  24582. * Gets the bounding box renderer associated with the scene
  24583. * @returns a BoundingBoxRenderer
  24584. */
  24585. Scene.prototype.getBoundingBoxRenderer = function () {
  24586. if (!this._boundingBoxRenderer) {
  24587. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  24588. }
  24589. return this._boundingBoxRenderer;
  24590. };
  24591. /**
  24592. * Gets the outline renderer associated with the scene
  24593. * @returns a OutlineRenderer
  24594. */
  24595. Scene.prototype.getOutlineRenderer = function () {
  24596. return this._outlineRenderer;
  24597. };
  24598. /**
  24599. * Gets the engine associated with the scene
  24600. * @returns an Engine
  24601. */
  24602. Scene.prototype.getEngine = function () {
  24603. return this._engine;
  24604. };
  24605. /**
  24606. * Gets the total number of vertices rendered per frame
  24607. * @returns the total number of vertices rendered per frame
  24608. */
  24609. Scene.prototype.getTotalVertices = function () {
  24610. return this._totalVertices.current;
  24611. };
  24612. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  24613. /**
  24614. * Gets the performance counter for total vertices
  24615. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24616. */
  24617. get: function () {
  24618. return this._totalVertices;
  24619. },
  24620. enumerable: true,
  24621. configurable: true
  24622. });
  24623. /**
  24624. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  24625. * @returns the total number of active indices rendered per frame
  24626. */
  24627. Scene.prototype.getActiveIndices = function () {
  24628. return this._activeIndices.current;
  24629. };
  24630. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  24631. /**
  24632. * Gets the performance counter for active indices
  24633. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24634. */
  24635. get: function () {
  24636. return this._activeIndices;
  24637. },
  24638. enumerable: true,
  24639. configurable: true
  24640. });
  24641. /**
  24642. * Gets the total number of active particles rendered per frame
  24643. * @returns the total number of active particles rendered per frame
  24644. */
  24645. Scene.prototype.getActiveParticles = function () {
  24646. return this._activeParticles.current;
  24647. };
  24648. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  24649. /**
  24650. * Gets the performance counter for active particles
  24651. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24652. */
  24653. get: function () {
  24654. return this._activeParticles;
  24655. },
  24656. enumerable: true,
  24657. configurable: true
  24658. });
  24659. /**
  24660. * Gets the total number of active bones rendered per frame
  24661. * @returns the total number of active bones rendered per frame
  24662. */
  24663. Scene.prototype.getActiveBones = function () {
  24664. return this._activeBones.current;
  24665. };
  24666. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  24667. /**
  24668. * Gets the performance counter for active bones
  24669. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24670. */
  24671. get: function () {
  24672. return this._activeBones;
  24673. },
  24674. enumerable: true,
  24675. configurable: true
  24676. });
  24677. /** @hidden */
  24678. Scene.prototype.getInterFramePerfCounter = function () {
  24679. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24680. return 0;
  24681. };
  24682. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  24683. /** @hidden */
  24684. get: function () {
  24685. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24686. return null;
  24687. },
  24688. enumerable: true,
  24689. configurable: true
  24690. });
  24691. /** @hidden */
  24692. Scene.prototype.getLastFrameDuration = function () {
  24693. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  24694. return 0;
  24695. };
  24696. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  24697. /** @hidden */
  24698. get: function () {
  24699. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24700. return null;
  24701. },
  24702. enumerable: true,
  24703. configurable: true
  24704. });
  24705. /** @hidden */
  24706. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  24707. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  24708. return 0;
  24709. };
  24710. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  24711. /** @hidden */
  24712. get: function () {
  24713. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24714. return null;
  24715. },
  24716. enumerable: true,
  24717. configurable: true
  24718. });
  24719. /**
  24720. * Gets the array of active meshes
  24721. * @returns an array of AbstractMesh
  24722. */
  24723. Scene.prototype.getActiveMeshes = function () {
  24724. return this._activeMeshes;
  24725. };
  24726. /** @hidden */
  24727. Scene.prototype.getRenderTargetsDuration = function () {
  24728. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  24729. return 0;
  24730. };
  24731. /** @hidden */
  24732. Scene.prototype.getRenderDuration = function () {
  24733. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  24734. return 0;
  24735. };
  24736. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  24737. /** @hidden */
  24738. get: function () {
  24739. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24740. return null;
  24741. },
  24742. enumerable: true,
  24743. configurable: true
  24744. });
  24745. /** @hidden */
  24746. Scene.prototype.getParticlesDuration = function () {
  24747. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  24748. return 0;
  24749. };
  24750. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  24751. /** @hidden */
  24752. get: function () {
  24753. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24754. return null;
  24755. },
  24756. enumerable: true,
  24757. configurable: true
  24758. });
  24759. /** @hidden */
  24760. Scene.prototype.getSpritesDuration = function () {
  24761. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  24762. return 0;
  24763. };
  24764. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  24765. /** @hidden */
  24766. get: function () {
  24767. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  24768. return null;
  24769. },
  24770. enumerable: true,
  24771. configurable: true
  24772. });
  24773. /**
  24774. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  24775. * @returns a number
  24776. */
  24777. Scene.prototype.getAnimationRatio = function () {
  24778. return this._animationRatio;
  24779. };
  24780. /**
  24781. * Gets an unique Id for the current frame
  24782. * @returns a number
  24783. */
  24784. Scene.prototype.getRenderId = function () {
  24785. return this._renderId;
  24786. };
  24787. /** Call this function if you want to manually increment the render Id*/
  24788. Scene.prototype.incrementRenderId = function () {
  24789. this._renderId++;
  24790. };
  24791. Scene.prototype._updatePointerPosition = function (evt) {
  24792. var canvasRect = this._engine.getRenderingCanvasClientRect();
  24793. if (!canvasRect) {
  24794. return;
  24795. }
  24796. this._pointerX = evt.clientX - canvasRect.left;
  24797. this._pointerY = evt.clientY - canvasRect.top;
  24798. this._unTranslatedPointerX = this._pointerX;
  24799. this._unTranslatedPointerY = this._pointerY;
  24800. };
  24801. Scene.prototype._createUbo = function () {
  24802. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24803. this._sceneUbo.addUniform("viewProjection", 16);
  24804. this._sceneUbo.addUniform("view", 16);
  24805. };
  24806. Scene.prototype._createAlternateUbo = function () {
  24807. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24808. this._alternateSceneUbo.addUniform("viewProjection", 16);
  24809. this._alternateSceneUbo.addUniform("view", 16);
  24810. };
  24811. // Pointers handling
  24812. /**
  24813. * Use this method to simulate a pointer move on a mesh
  24814. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24815. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24816. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24817. * @returns the current scene
  24818. */
  24819. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  24820. var evt = new PointerEvent("pointermove", pointerEventInit);
  24821. return this._processPointerMove(pickResult, evt);
  24822. };
  24823. Scene.prototype._processPointerMove = function (pickResult, evt) {
  24824. var canvas = this._engine.getRenderingCanvas();
  24825. if (!canvas) {
  24826. return this;
  24827. }
  24828. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  24829. this.setPointerOverSprite(null);
  24830. this.setPointerOverMesh(pickResult.pickedMesh);
  24831. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  24832. if (this._pointerOverMesh.actionManager.hoverCursor) {
  24833. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  24834. }
  24835. else {
  24836. canvas.style.cursor = this.hoverCursor;
  24837. }
  24838. }
  24839. else {
  24840. canvas.style.cursor = this.defaultCursor;
  24841. }
  24842. }
  24843. else {
  24844. this.setPointerOverMesh(null);
  24845. // Sprites
  24846. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  24847. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  24848. this.setPointerOverSprite(pickResult.pickedSprite);
  24849. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  24850. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  24851. }
  24852. else {
  24853. canvas.style.cursor = this.hoverCursor;
  24854. }
  24855. }
  24856. else {
  24857. this.setPointerOverSprite(null);
  24858. // Restore pointer
  24859. canvas.style.cursor = this.defaultCursor;
  24860. }
  24861. }
  24862. if (pickResult) {
  24863. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  24864. if (this.onPointerMove) {
  24865. this.onPointerMove(evt, pickResult, type);
  24866. }
  24867. if (this.onPointerObservable.hasObservers()) {
  24868. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24869. this.onPointerObservable.notifyObservers(pi, type);
  24870. }
  24871. }
  24872. return this;
  24873. };
  24874. /**
  24875. * Use this method to simulate a pointer down on a mesh
  24876. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24877. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24878. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24879. * @returns the current scene
  24880. */
  24881. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  24882. var evt = new PointerEvent("pointerdown", pointerEventInit);
  24883. return this._processPointerDown(pickResult, evt);
  24884. };
  24885. Scene.prototype._processPointerDown = function (pickResult, evt) {
  24886. var _this = this;
  24887. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  24888. this._pickedDownMesh = pickResult.pickedMesh;
  24889. var actionManager = pickResult.pickedMesh.actionManager;
  24890. if (actionManager) {
  24891. if (actionManager.hasPickTriggers) {
  24892. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24893. switch (evt.button) {
  24894. case 0:
  24895. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24896. break;
  24897. case 1:
  24898. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24899. break;
  24900. case 2:
  24901. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24902. break;
  24903. }
  24904. }
  24905. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  24906. window.setTimeout(function () {
  24907. 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);
  24908. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  24909. if (_this._totalPointersPressed !== 0 &&
  24910. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  24911. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  24912. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  24913. _this._startingPointerTime = 0;
  24914. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24915. }
  24916. }
  24917. }, Scene.LongPressDelay);
  24918. }
  24919. }
  24920. }
  24921. if (pickResult) {
  24922. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  24923. if (this.onPointerDown) {
  24924. this.onPointerDown(evt, pickResult, type);
  24925. }
  24926. if (this.onPointerObservable.hasObservers()) {
  24927. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24928. this.onPointerObservable.notifyObservers(pi, type);
  24929. }
  24930. }
  24931. return this;
  24932. };
  24933. /**
  24934. * Use this method to simulate a pointer up on a mesh
  24935. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24936. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24937. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24938. * @returns the current scene
  24939. */
  24940. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  24941. var evt = new PointerEvent("pointerup", pointerEventInit);
  24942. var clickInfo = new ClickInfo();
  24943. clickInfo.singleClick = true;
  24944. clickInfo.ignore = true;
  24945. return this._processPointerUp(pickResult, evt, clickInfo);
  24946. };
  24947. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  24948. if (pickResult && pickResult && pickResult.pickedMesh) {
  24949. this._pickedUpMesh = pickResult.pickedMesh;
  24950. if (this._pickedDownMesh === this._pickedUpMesh) {
  24951. if (this.onPointerPick) {
  24952. this.onPointerPick(evt, pickResult);
  24953. }
  24954. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  24955. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  24956. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  24957. this.onPointerObservable.notifyObservers(pi, type_1);
  24958. }
  24959. }
  24960. if (pickResult.pickedMesh.actionManager) {
  24961. if (clickInfo.ignore) {
  24962. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24963. }
  24964. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  24965. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24966. }
  24967. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  24968. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  24969. }
  24970. }
  24971. }
  24972. if (this._pickedDownMesh &&
  24973. this._pickedDownMesh.actionManager &&
  24974. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  24975. this._pickedDownMesh !== this._pickedUpMesh) {
  24976. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  24977. }
  24978. var type = BABYLON.PointerEventTypes.POINTERUP;
  24979. if (this.onPointerObservable.hasObservers()) {
  24980. if (!clickInfo.ignore) {
  24981. if (!clickInfo.hasSwiped) {
  24982. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  24983. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  24984. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  24985. this.onPointerObservable.notifyObservers(pi, type_2);
  24986. }
  24987. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  24988. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  24989. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  24990. this.onPointerObservable.notifyObservers(pi, type_3);
  24991. }
  24992. }
  24993. }
  24994. else {
  24995. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24996. this.onPointerObservable.notifyObservers(pi, type);
  24997. }
  24998. }
  24999. if (this.onPointerUp) {
  25000. this.onPointerUp(evt, pickResult, type);
  25001. }
  25002. return this;
  25003. };
  25004. /**
  25005. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25006. * @param attachUp defines if you want to attach events to pointerup
  25007. * @param attachDown defines if you want to attach events to pointerdown
  25008. * @param attachMove defines if you want to attach events to pointermove
  25009. */
  25010. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25011. var _this = this;
  25012. if (attachUp === void 0) { attachUp = true; }
  25013. if (attachDown === void 0) { attachDown = true; }
  25014. if (attachMove === void 0) { attachMove = true; }
  25015. this._initActionManager = function (act, clickInfo) {
  25016. if (!_this._meshPickProceed) {
  25017. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25018. _this._currentPickResult = pickResult;
  25019. if (pickResult) {
  25020. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25021. }
  25022. _this._meshPickProceed = true;
  25023. }
  25024. return act;
  25025. };
  25026. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25027. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25028. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25029. btn !== _this._previousButtonPressed) {
  25030. _this._doubleClickOccured = false;
  25031. clickInfo.singleClick = true;
  25032. clickInfo.ignore = false;
  25033. cb(clickInfo, _this._currentPickResult);
  25034. }
  25035. };
  25036. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25037. var clickInfo = new ClickInfo();
  25038. _this._currentPickResult = null;
  25039. var act = null;
  25040. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25041. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25042. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25043. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25044. act = _this._initActionManager(act, clickInfo);
  25045. if (act)
  25046. checkPicking = act.hasPickTriggers;
  25047. }
  25048. if (checkPicking) {
  25049. var btn = evt.button;
  25050. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  25051. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  25052. if (!clickInfo.hasSwiped) {
  25053. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25054. if (!checkSingleClickImmediately) {
  25055. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25056. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25057. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25058. act = _this._initActionManager(act, clickInfo);
  25059. if (act)
  25060. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25061. }
  25062. }
  25063. if (checkSingleClickImmediately) {
  25064. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25065. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25066. btn !== _this._previousButtonPressed) {
  25067. clickInfo.singleClick = true;
  25068. cb(clickInfo, _this._currentPickResult);
  25069. }
  25070. }
  25071. // at least one double click is required to be check and exclusive double click is enabled
  25072. else {
  25073. // wait that no double click has been raised during the double click delay
  25074. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25075. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25076. }
  25077. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25078. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25079. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25080. act = _this._initActionManager(act, clickInfo);
  25081. if (act)
  25082. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25083. }
  25084. if (checkDoubleClick) {
  25085. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25086. if (btn === _this._previousButtonPressed &&
  25087. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25088. !_this._doubleClickOccured) {
  25089. // pointer has not moved for 2 clicks, it's a double click
  25090. if (!clickInfo.hasSwiped &&
  25091. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  25092. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  25093. _this._previousStartingPointerTime = 0;
  25094. _this._doubleClickOccured = true;
  25095. clickInfo.doubleClick = true;
  25096. clickInfo.ignore = false;
  25097. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25098. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25099. }
  25100. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25101. cb(clickInfo, _this._currentPickResult);
  25102. }
  25103. // if the two successive clicks are too far, it's just two simple clicks
  25104. else {
  25105. _this._doubleClickOccured = false;
  25106. _this._previousStartingPointerTime = _this._startingPointerTime;
  25107. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25108. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25109. _this._previousButtonPressed = btn;
  25110. if (Scene.ExclusiveDoubleClickMode) {
  25111. if (_this._previousDelayedSimpleClickTimeout) {
  25112. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25113. }
  25114. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25115. cb(clickInfo, _this._previousPickResult);
  25116. }
  25117. else {
  25118. cb(clickInfo, _this._currentPickResult);
  25119. }
  25120. }
  25121. }
  25122. // just the first click of the double has been raised
  25123. else {
  25124. _this._doubleClickOccured = false;
  25125. _this._previousStartingPointerTime = _this._startingPointerTime;
  25126. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25127. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25128. _this._previousButtonPressed = btn;
  25129. }
  25130. }
  25131. }
  25132. }
  25133. clickInfo.ignore = true;
  25134. cb(clickInfo, _this._currentPickResult);
  25135. };
  25136. this._spritePredicate = function (sprite) {
  25137. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  25138. };
  25139. this._onPointerMove = function (evt) {
  25140. _this._updatePointerPosition(evt);
  25141. // PreObservable support
  25142. if (_this.onPrePointerObservable.hasObservers() && !_this._pointerCaptures[evt.pointerId]) {
  25143. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  25144. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25145. _this.onPrePointerObservable.notifyObservers(pi, type);
  25146. if (pi.skipOnPointerObservable) {
  25147. return;
  25148. }
  25149. }
  25150. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25151. return;
  25152. }
  25153. if (!_this.pointerMovePredicate) {
  25154. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25155. }
  25156. // Meshes
  25157. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25158. _this._processPointerMove(pickResult, evt);
  25159. };
  25160. this._onPointerDown = function (evt) {
  25161. _this._totalPointersPressed++;
  25162. _this._pickedDownMesh = null;
  25163. _this._meshPickProceed = false;
  25164. _this._updatePointerPosition(evt);
  25165. if (_this.preventDefaultOnPointerDown && canvas) {
  25166. evt.preventDefault();
  25167. canvas.focus();
  25168. }
  25169. // PreObservable support
  25170. if (_this.onPrePointerObservable.hasObservers()) {
  25171. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25172. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25173. _this.onPrePointerObservable.notifyObservers(pi, type);
  25174. if (pi.skipOnPointerObservable) {
  25175. return;
  25176. }
  25177. }
  25178. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25179. return;
  25180. }
  25181. _this._pointerCaptures[evt.pointerId] = true;
  25182. _this._startingPointerPosition.x = _this._pointerX;
  25183. _this._startingPointerPosition.y = _this._pointerY;
  25184. _this._startingPointerTime = Date.now();
  25185. if (!_this.pointerDownPredicate) {
  25186. _this.pointerDownPredicate = function (mesh) {
  25187. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25188. };
  25189. }
  25190. // Meshes
  25191. _this._pickedDownMesh = null;
  25192. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25193. _this._processPointerDown(pickResult, evt);
  25194. // Sprites
  25195. _this._pickedDownSprite = null;
  25196. if (_this.spriteManagers.length > 0) {
  25197. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25198. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25199. if (pickResult.pickedSprite.actionManager) {
  25200. _this._pickedDownSprite = pickResult.pickedSprite;
  25201. switch (evt.button) {
  25202. case 0:
  25203. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25204. break;
  25205. case 1:
  25206. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25207. break;
  25208. case 2:
  25209. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25210. break;
  25211. }
  25212. if (pickResult.pickedSprite.actionManager) {
  25213. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25214. }
  25215. }
  25216. }
  25217. }
  25218. };
  25219. this._onPointerUp = function (evt) {
  25220. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25221. return; // So we need to test it the pointer down was pressed before.
  25222. }
  25223. _this._totalPointersPressed--;
  25224. _this._pickedUpMesh = null;
  25225. _this._meshPickProceed = false;
  25226. _this._updatePointerPosition(evt);
  25227. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25228. // PreObservable support
  25229. if (_this.onPrePointerObservable.hasObservers() && !_this._pointerCaptures[evt.pointerId]) {
  25230. if (!clickInfo.ignore) {
  25231. if (!clickInfo.hasSwiped) {
  25232. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25233. var type = BABYLON.PointerEventTypes.POINTERTAP;
  25234. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25235. _this.onPrePointerObservable.notifyObservers(pi, type);
  25236. if (pi.skipOnPointerObservable) {
  25237. return;
  25238. }
  25239. }
  25240. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25241. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25242. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25243. _this.onPrePointerObservable.notifyObservers(pi, type);
  25244. if (pi.skipOnPointerObservable) {
  25245. return;
  25246. }
  25247. }
  25248. }
  25249. }
  25250. else {
  25251. var type = BABYLON.PointerEventTypes.POINTERUP;
  25252. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25253. _this.onPrePointerObservable.notifyObservers(pi, type);
  25254. if (pi.skipOnPointerObservable) {
  25255. return;
  25256. }
  25257. }
  25258. }
  25259. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25260. return;
  25261. }
  25262. _this._pointerCaptures[evt.pointerId] = false;
  25263. if (!_this.pointerUpPredicate) {
  25264. _this.pointerUpPredicate = function (mesh) {
  25265. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25266. };
  25267. }
  25268. // Meshes
  25269. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25270. _this._initActionManager(null, clickInfo);
  25271. }
  25272. if (!pickResult) {
  25273. pickResult = _this._currentPickResult;
  25274. }
  25275. _this._processPointerUp(pickResult, evt, clickInfo);
  25276. // Sprites
  25277. if (!clickInfo.ignore) {
  25278. if (_this.spriteManagers.length > 0) {
  25279. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25280. if (spritePickResult) {
  25281. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  25282. if (spritePickResult.pickedSprite.actionManager) {
  25283. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25284. if (spritePickResult.pickedSprite.actionManager) {
  25285. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  25286. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25287. }
  25288. }
  25289. }
  25290. }
  25291. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  25292. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  25293. }
  25294. }
  25295. }
  25296. }
  25297. _this._previousPickResult = _this._currentPickResult;
  25298. });
  25299. };
  25300. this._onKeyDown = function (evt) {
  25301. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25302. if (_this.onPreKeyboardObservable.hasObservers()) {
  25303. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25304. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25305. if (pi.skipOnPointerObservable) {
  25306. return;
  25307. }
  25308. }
  25309. if (_this.onKeyboardObservable.hasObservers()) {
  25310. var pi = new BABYLON.KeyboardInfo(type, evt);
  25311. _this.onKeyboardObservable.notifyObservers(pi, type);
  25312. }
  25313. if (_this.actionManager) {
  25314. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25315. }
  25316. };
  25317. this._onKeyUp = function (evt) {
  25318. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25319. if (_this.onPreKeyboardObservable.hasObservers()) {
  25320. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25321. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25322. if (pi.skipOnPointerObservable) {
  25323. return;
  25324. }
  25325. }
  25326. if (_this.onKeyboardObservable.hasObservers()) {
  25327. var pi = new BABYLON.KeyboardInfo(type, evt);
  25328. _this.onKeyboardObservable.notifyObservers(pi, type);
  25329. }
  25330. if (_this.actionManager) {
  25331. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25332. }
  25333. };
  25334. var engine = this.getEngine();
  25335. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25336. if (!canvas) {
  25337. return;
  25338. }
  25339. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25340. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25341. });
  25342. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25343. if (!canvas) {
  25344. return;
  25345. }
  25346. canvas.removeEventListener("keydown", _this._onKeyDown);
  25347. canvas.removeEventListener("keyup", _this._onKeyUp);
  25348. });
  25349. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25350. var canvas = this._engine.getRenderingCanvas();
  25351. if (!canvas) {
  25352. return;
  25353. }
  25354. if (attachMove) {
  25355. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25356. // Wheel
  25357. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25358. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25359. }
  25360. if (attachDown) {
  25361. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25362. }
  25363. if (attachUp) {
  25364. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25365. }
  25366. canvas.tabIndex = 1;
  25367. };
  25368. /** Detaches all event handlers*/
  25369. Scene.prototype.detachControl = function () {
  25370. var engine = this.getEngine();
  25371. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25372. var canvas = engine.getRenderingCanvas();
  25373. if (!canvas) {
  25374. return;
  25375. }
  25376. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25377. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25378. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25379. if (this._onCanvasBlurObserver) {
  25380. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25381. }
  25382. if (this._onCanvasFocusObserver) {
  25383. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25384. }
  25385. // Wheel
  25386. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25387. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25388. // Keyboard
  25389. canvas.removeEventListener("keydown", this._onKeyDown);
  25390. canvas.removeEventListener("keyup", this._onKeyUp);
  25391. // Observables
  25392. this.onKeyboardObservable.clear();
  25393. this.onPreKeyboardObservable.clear();
  25394. this.onPointerObservable.clear();
  25395. this.onPrePointerObservable.clear();
  25396. };
  25397. /**
  25398. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25399. * Delay loaded resources are not taking in account
  25400. * @return true if all required resources are ready
  25401. */
  25402. Scene.prototype.isReady = function () {
  25403. if (this._isDisposed) {
  25404. return false;
  25405. }
  25406. if (this._pendingData.length > 0) {
  25407. return false;
  25408. }
  25409. var index;
  25410. var engine = this.getEngine();
  25411. // Geometries
  25412. for (index = 0; index < this._geometries.length; index++) {
  25413. var geometry = this._geometries[index];
  25414. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25415. return false;
  25416. }
  25417. }
  25418. // Meshes
  25419. for (index = 0; index < this.meshes.length; index++) {
  25420. var mesh = this.meshes[index];
  25421. if (!mesh.isEnabled()) {
  25422. continue;
  25423. }
  25424. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25425. continue;
  25426. }
  25427. if (!mesh.isReady(true)) {
  25428. return false;
  25429. }
  25430. // Effect layers
  25431. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25432. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  25433. var layer = _a[_i];
  25434. if (!layer.hasMesh(mesh)) {
  25435. continue;
  25436. }
  25437. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  25438. var subMesh = _c[_b];
  25439. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  25440. return false;
  25441. }
  25442. }
  25443. }
  25444. }
  25445. // Post-processes
  25446. if (this.activeCameras && this.activeCameras.length > 0) {
  25447. for (var _d = 0, _e = this.activeCameras; _d < _e.length; _d++) {
  25448. var camera = _e[_d];
  25449. if (!camera.isReady(true)) {
  25450. return false;
  25451. }
  25452. }
  25453. }
  25454. else if (this.activeCamera) {
  25455. if (!this.activeCamera.isReady(true)) {
  25456. return false;
  25457. }
  25458. }
  25459. // Particles
  25460. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  25461. var particleSystem = _g[_f];
  25462. if (!particleSystem.isReady()) {
  25463. return false;
  25464. }
  25465. }
  25466. return true;
  25467. };
  25468. /** Resets all cached information relative to material (including effect and visibility) */
  25469. Scene.prototype.resetCachedMaterial = function () {
  25470. this._cachedMaterial = null;
  25471. this._cachedEffect = null;
  25472. this._cachedVisibility = null;
  25473. };
  25474. /**
  25475. * Registers a function to be called before every frame render
  25476. * @param func defines the function to register
  25477. */
  25478. Scene.prototype.registerBeforeRender = function (func) {
  25479. this.onBeforeRenderObservable.add(func);
  25480. };
  25481. /**
  25482. * Unregisters a function called before every frame render
  25483. * @param func defines the function to unregister
  25484. */
  25485. Scene.prototype.unregisterBeforeRender = function (func) {
  25486. this.onBeforeRenderObservable.removeCallback(func);
  25487. };
  25488. /**
  25489. * Registers a function to be called after every frame render
  25490. * @param func defines the function to register
  25491. */
  25492. Scene.prototype.registerAfterRender = function (func) {
  25493. this.onAfterRenderObservable.add(func);
  25494. };
  25495. /**
  25496. * Unregisters a function called after every frame render
  25497. * @param func defines the function to unregister
  25498. */
  25499. Scene.prototype.unregisterAfterRender = function (func) {
  25500. this.onAfterRenderObservable.removeCallback(func);
  25501. };
  25502. Scene.prototype._executeOnceBeforeRender = function (func) {
  25503. var _this = this;
  25504. var execFunc = function () {
  25505. func();
  25506. setTimeout(function () {
  25507. _this.unregisterBeforeRender(execFunc);
  25508. });
  25509. };
  25510. this.registerBeforeRender(execFunc);
  25511. };
  25512. /**
  25513. * The provided function will run before render once and will be disposed afterwards.
  25514. * A timeout delay can be provided so that the function will be executed in N ms.
  25515. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  25516. * @param func The function to be executed.
  25517. * @param timeout optional delay in ms
  25518. */
  25519. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  25520. var _this = this;
  25521. if (timeout !== undefined) {
  25522. setTimeout(function () {
  25523. _this._executeOnceBeforeRender(func);
  25524. }, timeout);
  25525. }
  25526. else {
  25527. this._executeOnceBeforeRender(func);
  25528. }
  25529. };
  25530. /** @hidden */
  25531. Scene.prototype._addPendingData = function (data) {
  25532. this._pendingData.push(data);
  25533. };
  25534. /** @hidden */
  25535. Scene.prototype._removePendingData = function (data) {
  25536. var wasLoading = this.isLoading;
  25537. var index = this._pendingData.indexOf(data);
  25538. if (index !== -1) {
  25539. this._pendingData.splice(index, 1);
  25540. }
  25541. if (wasLoading && !this.isLoading) {
  25542. this.onDataLoadedObservable.notifyObservers(this);
  25543. }
  25544. };
  25545. /**
  25546. * Returns the number of items waiting to be loaded
  25547. * @returns the number of items waiting to be loaded
  25548. */
  25549. Scene.prototype.getWaitingItemsCount = function () {
  25550. return this._pendingData.length;
  25551. };
  25552. Object.defineProperty(Scene.prototype, "isLoading", {
  25553. /**
  25554. * Returns a boolean indicating if the scene is still loading data
  25555. */
  25556. get: function () {
  25557. return this._pendingData.length > 0;
  25558. },
  25559. enumerable: true,
  25560. configurable: true
  25561. });
  25562. /**
  25563. * Registers a function to be executed when the scene is ready
  25564. * @param {Function} func - the function to be executed
  25565. */
  25566. Scene.prototype.executeWhenReady = function (func) {
  25567. var _this = this;
  25568. this.onReadyObservable.add(func);
  25569. if (this._executeWhenReadyTimeoutId !== -1) {
  25570. return;
  25571. }
  25572. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25573. _this._checkIsReady();
  25574. }, 150);
  25575. };
  25576. /**
  25577. * Returns a promise that resolves when the scene is ready
  25578. * @returns A promise that resolves when the scene is ready
  25579. */
  25580. Scene.prototype.whenReadyAsync = function () {
  25581. var _this = this;
  25582. return new Promise(function (resolve) {
  25583. _this.executeWhenReady(function () {
  25584. resolve();
  25585. });
  25586. });
  25587. };
  25588. /** @hidden */
  25589. Scene.prototype._checkIsReady = function () {
  25590. var _this = this;
  25591. if (this.isReady()) {
  25592. this.onReadyObservable.notifyObservers(this);
  25593. this.onReadyObservable.clear();
  25594. this._executeWhenReadyTimeoutId = -1;
  25595. return;
  25596. }
  25597. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25598. _this._checkIsReady();
  25599. }, 150);
  25600. };
  25601. // Animations
  25602. /**
  25603. * Will start the animation sequence of a given target
  25604. * @param target defines the target
  25605. * @param from defines from which frame should animation start
  25606. * @param to defines until which frame should animation run.
  25607. * @param weight defines the weight to apply to the animation (1.0 by default)
  25608. * @param loop defines if the animation loops
  25609. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25610. * @param onAnimationEnd defines the function to be executed when the animation ends
  25611. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25612. * @returns the animatable object created for this animation
  25613. */
  25614. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  25615. if (weight === void 0) { weight = 1.0; }
  25616. if (speedRatio === void 0) { speedRatio = 1.0; }
  25617. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  25618. returnedAnimatable.weight = weight;
  25619. return returnedAnimatable;
  25620. };
  25621. /**
  25622. * Will start the animation sequence of a given target
  25623. * @param target defines the target
  25624. * @param from defines from which frame should animation start
  25625. * @param to defines until which frame should animation run.
  25626. * @param loop defines if the animation loops
  25627. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25628. * @param onAnimationEnd defines the function to be executed when the animation ends
  25629. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25630. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  25631. * @returns the animatable object created for this animation
  25632. */
  25633. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  25634. if (speedRatio === void 0) { speedRatio = 1.0; }
  25635. if (stopCurrent === void 0) { stopCurrent = true; }
  25636. if (from > to && speedRatio > 0) {
  25637. speedRatio *= -1;
  25638. }
  25639. if (stopCurrent) {
  25640. this.stopAnimation(target);
  25641. }
  25642. if (!animatable) {
  25643. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  25644. }
  25645. // Local animations
  25646. if (target.animations) {
  25647. animatable.appendAnimations(target, target.animations);
  25648. }
  25649. // Children animations
  25650. if (target.getAnimatables) {
  25651. var animatables = target.getAnimatables();
  25652. for (var index = 0; index < animatables.length; index++) {
  25653. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  25654. }
  25655. }
  25656. animatable.reset();
  25657. return animatable;
  25658. };
  25659. /**
  25660. * Begin a new animation on a given node
  25661. * @param target defines the target where the animation will take place
  25662. * @param animations defines the list of animations to start
  25663. * @param from defines the initial value
  25664. * @param to defines the final value
  25665. * @param loop defines if you want animation to loop (off by default)
  25666. * @param speedRatio defines the speed ratio to apply to all animations
  25667. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25668. * @returns the list of created animatables
  25669. */
  25670. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25671. if (speedRatio === undefined) {
  25672. speedRatio = 1.0;
  25673. }
  25674. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  25675. return animatable;
  25676. };
  25677. /**
  25678. * Begin a new animation on a given node and its hierarchy
  25679. * @param target defines the root node where the animation will take place
  25680. * @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.
  25681. * @param animations defines the list of animations to start
  25682. * @param from defines the initial value
  25683. * @param to defines the final value
  25684. * @param loop defines if you want animation to loop (off by default)
  25685. * @param speedRatio defines the speed ratio to apply to all animations
  25686. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25687. * @returns the list of animatables created for all nodes
  25688. */
  25689. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25690. var children = target.getDescendants(directDescendantsOnly);
  25691. var result = [];
  25692. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  25693. var child = children_1[_i];
  25694. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  25695. }
  25696. return result;
  25697. };
  25698. /**
  25699. * Gets the animatable associated with a specific target
  25700. * @param target defines the target of the animatable
  25701. * @returns the required animatable if found
  25702. */
  25703. Scene.prototype.getAnimatableByTarget = function (target) {
  25704. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25705. if (this._activeAnimatables[index].target === target) {
  25706. return this._activeAnimatables[index];
  25707. }
  25708. }
  25709. return null;
  25710. };
  25711. /**
  25712. * Gets all animatables associated with a given target
  25713. * @param target defines the target to look animatables for
  25714. * @returns an array of Animatables
  25715. */
  25716. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  25717. var result = [];
  25718. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25719. if (this._activeAnimatables[index].target === target) {
  25720. result.push(this._activeAnimatables[index]);
  25721. }
  25722. }
  25723. return result;
  25724. };
  25725. Object.defineProperty(Scene.prototype, "animatables", {
  25726. /**
  25727. * Gets all animatable attached to the scene
  25728. */
  25729. get: function () {
  25730. return this._activeAnimatables;
  25731. },
  25732. enumerable: true,
  25733. configurable: true
  25734. });
  25735. /**
  25736. * Will stop the animation of the given target
  25737. * @param target - the target
  25738. * @param animationName - the name of the animation to stop (all animations will be stopped if empty)
  25739. */
  25740. Scene.prototype.stopAnimation = function (target, animationName) {
  25741. var animatables = this.getAllAnimatablesByTarget(target);
  25742. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  25743. var animatable = animatables_1[_i];
  25744. animatable.stop(animationName);
  25745. }
  25746. };
  25747. /**
  25748. * Stops and removes all animations that have been applied to the scene
  25749. */
  25750. Scene.prototype.stopAllAnimations = function () {
  25751. if (this._activeAnimatables) {
  25752. for (var i = 0; i < this._activeAnimatables.length; i++) {
  25753. this._activeAnimatables[i].stop();
  25754. }
  25755. this._activeAnimatables = [];
  25756. }
  25757. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  25758. var group = _a[_i];
  25759. group.stop();
  25760. }
  25761. };
  25762. Scene.prototype._animate = function () {
  25763. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  25764. return;
  25765. }
  25766. // Getting time
  25767. var now = BABYLON.Tools.Now;
  25768. if (!this._animationTimeLast) {
  25769. if (this._pendingData.length > 0) {
  25770. return;
  25771. }
  25772. this._animationTimeLast = now;
  25773. }
  25774. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  25775. this._animationTime += deltaTime;
  25776. this._animationTimeLast = now;
  25777. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25778. this._activeAnimatables[index]._animate(this._animationTime);
  25779. }
  25780. // Late animation bindings
  25781. this._processLateAnimationBindings();
  25782. };
  25783. /** @hidden */
  25784. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  25785. var target = runtimeAnimation.target;
  25786. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  25787. if (!target._lateAnimationHolders) {
  25788. target._lateAnimationHolders = {};
  25789. }
  25790. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  25791. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  25792. totalWeight: 0,
  25793. animations: [],
  25794. originalValue: originalValue
  25795. };
  25796. }
  25797. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  25798. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  25799. };
  25800. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  25801. var normalizer = 1.0;
  25802. var finalPosition = BABYLON.Tmp.Vector3[0];
  25803. var finalScaling = BABYLON.Tmp.Vector3[1];
  25804. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  25805. var startIndex = 0;
  25806. var originalAnimation = holder.animations[0];
  25807. var originalValue = holder.originalValue;
  25808. var scale = 1;
  25809. if (holder.totalWeight < 1.0) {
  25810. // We need to mix the original value in
  25811. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  25812. scale = 1.0 - holder.totalWeight;
  25813. }
  25814. else {
  25815. startIndex = 1;
  25816. // We need to normalize the weights
  25817. normalizer = holder.totalWeight;
  25818. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  25819. scale = originalAnimation.weight / normalizer;
  25820. if (scale == 1) {
  25821. return originalAnimation.currentValue;
  25822. }
  25823. }
  25824. finalScaling.scaleInPlace(scale);
  25825. finalPosition.scaleInPlace(scale);
  25826. finalQuaternion.scaleInPlace(scale);
  25827. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  25828. var runtimeAnimation = holder.animations[animIndex];
  25829. var scale = runtimeAnimation.weight / normalizer;
  25830. var currentPosition = BABYLON.Tmp.Vector3[2];
  25831. var currentScaling = BABYLON.Tmp.Vector3[3];
  25832. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  25833. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  25834. currentScaling.scaleAndAddToRef(scale, finalScaling);
  25835. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  25836. currentPosition.scaleAndAddToRef(scale, finalPosition);
  25837. }
  25838. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  25839. return originalAnimation._workValue;
  25840. };
  25841. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder) {
  25842. var originalAnimation = holder.animations[0];
  25843. var originalValue = holder.originalValue;
  25844. if (holder.animations.length === 1) {
  25845. return BABYLON.Quaternion.Slerp(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight));
  25846. }
  25847. var normalizer = 1.0;
  25848. var quaternions;
  25849. var weights;
  25850. if (holder.totalWeight < 1.0) {
  25851. var scale = 1.0 - holder.totalWeight;
  25852. quaternions = [];
  25853. weights = [];
  25854. quaternions.push(originalValue);
  25855. weights.push(scale);
  25856. }
  25857. else {
  25858. if (holder.animations.length === 2) { // Slerp as soon as we can
  25859. return BABYLON.Quaternion.Slerp(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight);
  25860. }
  25861. quaternions = [];
  25862. weights = [];
  25863. normalizer = holder.totalWeight;
  25864. }
  25865. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  25866. var runtimeAnimation = holder.animations[animIndex];
  25867. quaternions.push(runtimeAnimation.currentValue);
  25868. weights.push(runtimeAnimation.weight / normalizer);
  25869. }
  25870. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  25871. var cumulativeAmount = 0;
  25872. var cumulativeQuaternion = null;
  25873. for (var index = 0; index < quaternions.length;) {
  25874. if (!cumulativeQuaternion) {
  25875. cumulativeQuaternion = BABYLON.Quaternion.Slerp(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]));
  25876. cumulativeAmount = weights[index] + weights[index + 1];
  25877. index += 2;
  25878. continue;
  25879. }
  25880. cumulativeAmount += weights[index];
  25881. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  25882. index++;
  25883. }
  25884. return cumulativeQuaternion;
  25885. };
  25886. Scene.prototype._processLateAnimationBindings = function () {
  25887. if (!this._registeredForLateAnimationBindings.length) {
  25888. return;
  25889. }
  25890. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  25891. var target = this._registeredForLateAnimationBindings.data[index];
  25892. for (var path in target._lateAnimationHolders) {
  25893. var holder = target._lateAnimationHolders[path];
  25894. var originalAnimation = holder.animations[0];
  25895. var originalValue = holder.originalValue;
  25896. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  25897. var finalValue = void 0;
  25898. if (matrixDecomposeMode) {
  25899. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  25900. }
  25901. else {
  25902. var quaternionMode = originalValue.w !== undefined;
  25903. if (quaternionMode) {
  25904. finalValue = this._processLateAnimationBindingsForQuaternions(holder);
  25905. }
  25906. else {
  25907. var startIndex = 0;
  25908. var normalizer = 1.0;
  25909. if (holder.totalWeight < 1.0) {
  25910. // We need to mix the original value in
  25911. if (originalValue.scale) {
  25912. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  25913. }
  25914. else {
  25915. finalValue = originalValue * (1.0 - holder.totalWeight);
  25916. }
  25917. }
  25918. else {
  25919. // We need to normalize the weights
  25920. normalizer = holder.totalWeight;
  25921. var scale_1 = originalAnimation.weight / normalizer;
  25922. if (scale_1 !== 1) {
  25923. if (originalAnimation.currentValue.scale) {
  25924. finalValue = originalAnimation.currentValue.scale(scale_1);
  25925. }
  25926. else {
  25927. finalValue = originalAnimation.currentValue * scale_1;
  25928. }
  25929. }
  25930. else {
  25931. finalValue = originalAnimation.currentValue;
  25932. }
  25933. startIndex = 1;
  25934. }
  25935. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  25936. var runtimeAnimation = holder.animations[animIndex];
  25937. var scale = runtimeAnimation.weight / normalizer;
  25938. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  25939. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  25940. }
  25941. else {
  25942. finalValue += runtimeAnimation.currentValue * scale;
  25943. }
  25944. }
  25945. }
  25946. }
  25947. target[path] = finalValue;
  25948. }
  25949. target._lateAnimationHolders = {};
  25950. }
  25951. this._registeredForLateAnimationBindings.reset();
  25952. };
  25953. // Matrix
  25954. /** @hidden */
  25955. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  25956. this._useAlternateCameraConfiguration = active;
  25957. };
  25958. /**
  25959. * Gets the current view matrix
  25960. * @returns a Matrix
  25961. */
  25962. Scene.prototype.getViewMatrix = function () {
  25963. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  25964. };
  25965. /**
  25966. * Gets the current projection matrix
  25967. * @returns a Matrix
  25968. */
  25969. Scene.prototype.getProjectionMatrix = function () {
  25970. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  25971. };
  25972. /**
  25973. * Gets the current transform matrix
  25974. * @returns a Matrix made of View * Projection
  25975. */
  25976. Scene.prototype.getTransformMatrix = function () {
  25977. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  25978. };
  25979. /**
  25980. * Sets the current transform matrix
  25981. * @param view defines the View matrix to use
  25982. * @param projection defines the Projection matrix to use
  25983. */
  25984. Scene.prototype.setTransformMatrix = function (view, projection) {
  25985. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  25986. return;
  25987. }
  25988. this._viewUpdateFlag = view.updateFlag;
  25989. this._projectionUpdateFlag = projection.updateFlag;
  25990. this._viewMatrix = view;
  25991. this._projectionMatrix = projection;
  25992. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  25993. // Update frustum
  25994. if (!this._frustumPlanes) {
  25995. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  25996. }
  25997. else {
  25998. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  25999. }
  26000. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26001. var otherCamera = this.activeCamera._alternateCamera;
  26002. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26003. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26004. }
  26005. if (this._sceneUbo.useUbo) {
  26006. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26007. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26008. this._sceneUbo.update();
  26009. }
  26010. };
  26011. /** @hidden */
  26012. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26013. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26014. return;
  26015. }
  26016. this._alternateViewUpdateFlag = view.updateFlag;
  26017. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26018. this._alternateViewMatrix = view;
  26019. this._alternateProjectionMatrix = projection;
  26020. if (!this._alternateTransformMatrix) {
  26021. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26022. }
  26023. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26024. if (!this._alternateSceneUbo) {
  26025. this._createAlternateUbo();
  26026. }
  26027. if (this._alternateSceneUbo.useUbo) {
  26028. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26029. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26030. this._alternateSceneUbo.update();
  26031. }
  26032. };
  26033. /**
  26034. * Gets the uniform buffer used to store scene data
  26035. * @returns a UniformBuffer
  26036. */
  26037. Scene.prototype.getSceneUniformBuffer = function () {
  26038. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26039. };
  26040. /**
  26041. * Gets an unique (relatively to the current scene) Id
  26042. * @returns an unique number for the scene
  26043. */
  26044. Scene.prototype.getUniqueId = function () {
  26045. var result = Scene._uniqueIdCounter;
  26046. Scene._uniqueIdCounter++;
  26047. return result;
  26048. };
  26049. /**
  26050. * Add a mesh to the list of scene's meshes
  26051. * @param newMesh defines the mesh to add
  26052. */
  26053. Scene.prototype.addMesh = function (newMesh) {
  26054. this.meshes.push(newMesh);
  26055. //notify the collision coordinator
  26056. if (this.collisionCoordinator) {
  26057. this.collisionCoordinator.onMeshAdded(newMesh);
  26058. }
  26059. newMesh._resyncLightSources();
  26060. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26061. };
  26062. /**
  26063. * Remove a mesh for the list of scene's meshes
  26064. * @param toRemove defines the mesh to remove
  26065. * @param recursive if all child meshes should also be removed from the scene
  26066. * @returns the index where the mesh was in the mesh list
  26067. */
  26068. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26069. var _this = this;
  26070. if (recursive === void 0) { recursive = false; }
  26071. var index = this.meshes.indexOf(toRemove);
  26072. if (index !== -1) {
  26073. // Remove from the scene if mesh found
  26074. this.meshes.splice(index, 1);
  26075. }
  26076. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26077. if (recursive) {
  26078. toRemove.getChildMeshes().forEach(function (m) {
  26079. _this.removeMesh(m);
  26080. });
  26081. }
  26082. return index;
  26083. };
  26084. /**
  26085. * Add a transform node to the list of scene's transform nodes
  26086. * @param newTransformNode defines the transform node to add
  26087. */
  26088. Scene.prototype.addTransformNode = function (newTransformNode) {
  26089. this.transformNodes.push(newTransformNode);
  26090. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26091. };
  26092. /**
  26093. * Remove a transform node for the list of scene's transform nodes
  26094. * @param toRemove defines the transform node to remove
  26095. * @returns the index where the transform node was in the transform node list
  26096. */
  26097. Scene.prototype.removeTransformNode = function (toRemove) {
  26098. var index = this.transformNodes.indexOf(toRemove);
  26099. if (index !== -1) {
  26100. // Remove from the scene if found
  26101. this.transformNodes.splice(index, 1);
  26102. }
  26103. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26104. return index;
  26105. };
  26106. /**
  26107. * Remove a skeleton for the list of scene's skeletons
  26108. * @param toRemove defines the skeleton to remove
  26109. * @returns the index where the skeleton was in the skeleton list
  26110. */
  26111. Scene.prototype.removeSkeleton = function (toRemove) {
  26112. var index = this.skeletons.indexOf(toRemove);
  26113. if (index !== -1) {
  26114. // Remove from the scene if found
  26115. this.skeletons.splice(index, 1);
  26116. }
  26117. return index;
  26118. };
  26119. /**
  26120. * Remove a morph target for the list of scene's morph targets
  26121. * @param toRemove defines the morph target to remove
  26122. * @returns the index where the morph target was in the morph target list
  26123. */
  26124. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26125. var index = this.morphTargetManagers.indexOf(toRemove);
  26126. if (index !== -1) {
  26127. // Remove from the scene if found
  26128. this.morphTargetManagers.splice(index, 1);
  26129. }
  26130. return index;
  26131. };
  26132. /**
  26133. * Remove a light for the list of scene's lights
  26134. * @param toRemove defines the light to remove
  26135. * @returns the index where the light was in the light list
  26136. */
  26137. Scene.prototype.removeLight = function (toRemove) {
  26138. var index = this.lights.indexOf(toRemove);
  26139. if (index !== -1) {
  26140. // Remove from meshes
  26141. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26142. var mesh = _a[_i];
  26143. mesh._removeLightSource(toRemove);
  26144. }
  26145. // Remove from the scene if mesh found
  26146. this.lights.splice(index, 1);
  26147. this.sortLightsByPriority();
  26148. }
  26149. this.onLightRemovedObservable.notifyObservers(toRemove);
  26150. return index;
  26151. };
  26152. /**
  26153. * Remove a camera for the list of scene's cameras
  26154. * @param toRemove defines the camera to remove
  26155. * @returns the index where the camera was in the camera list
  26156. */
  26157. Scene.prototype.removeCamera = function (toRemove) {
  26158. var index = this.cameras.indexOf(toRemove);
  26159. if (index !== -1) {
  26160. // Remove from the scene if mesh found
  26161. this.cameras.splice(index, 1);
  26162. }
  26163. // Remove from activeCameras
  26164. var index2 = this.activeCameras.indexOf(toRemove);
  26165. if (index2 !== -1) {
  26166. // Remove from the scene if mesh found
  26167. this.activeCameras.splice(index2, 1);
  26168. }
  26169. // Reset the activeCamera
  26170. if (this.activeCamera === toRemove) {
  26171. if (this.cameras.length > 0) {
  26172. this.activeCamera = this.cameras[0];
  26173. }
  26174. else {
  26175. this.activeCamera = null;
  26176. }
  26177. }
  26178. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26179. return index;
  26180. };
  26181. /**
  26182. * Remove a particle system for the list of scene's particle systems
  26183. * @param toRemove defines the particle system to remove
  26184. * @returns the index where the particle system was in the particle system list
  26185. */
  26186. Scene.prototype.removeParticleSystem = function (toRemove) {
  26187. var index = this.particleSystems.indexOf(toRemove);
  26188. if (index !== -1) {
  26189. this.particleSystems.splice(index, 1);
  26190. }
  26191. return index;
  26192. };
  26193. /**
  26194. * Remove a animation for the list of scene's animations
  26195. * @param toRemove defines the animation to remove
  26196. * @returns the index where the animation was in the animation list
  26197. */
  26198. Scene.prototype.removeAnimation = function (toRemove) {
  26199. var index = this.animations.indexOf(toRemove);
  26200. if (index !== -1) {
  26201. this.animations.splice(index, 1);
  26202. }
  26203. return index;
  26204. };
  26205. /**
  26206. * Removes the given animation group from this scene.
  26207. * @param toRemove The animation group to remove
  26208. * @returns The index of the removed animation group
  26209. */
  26210. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26211. var index = this.animationGroups.indexOf(toRemove);
  26212. if (index !== -1) {
  26213. this.animationGroups.splice(index, 1);
  26214. }
  26215. return index;
  26216. };
  26217. /**
  26218. * Removes the given multi-material from this scene.
  26219. * @param toRemove The multi-material to remove
  26220. * @returns The index of the removed multi-material
  26221. */
  26222. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26223. var index = this.multiMaterials.indexOf(toRemove);
  26224. if (index !== -1) {
  26225. this.multiMaterials.splice(index, 1);
  26226. }
  26227. return index;
  26228. };
  26229. /**
  26230. * Removes the given material from this scene.
  26231. * @param toRemove The material to remove
  26232. * @returns The index of the removed material
  26233. */
  26234. Scene.prototype.removeMaterial = function (toRemove) {
  26235. var index = this.materials.indexOf(toRemove);
  26236. if (index !== -1) {
  26237. this.materials.splice(index, 1);
  26238. }
  26239. return index;
  26240. };
  26241. /**
  26242. * Removes the given lens flare system from this scene.
  26243. * @param toRemove The lens flare system to remove
  26244. * @returns The index of the removed lens flare system
  26245. */
  26246. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  26247. var index = this.lensFlareSystems.indexOf(toRemove);
  26248. if (index !== -1) {
  26249. this.lensFlareSystems.splice(index, 1);
  26250. }
  26251. return index;
  26252. };
  26253. /**
  26254. * Removes the given action manager from this scene.
  26255. * @param toRemove The action manager to remove
  26256. * @returns The index of the removed action manager
  26257. */
  26258. Scene.prototype.removeActionManager = function (toRemove) {
  26259. var index = this._actionManagers.indexOf(toRemove);
  26260. if (index !== -1) {
  26261. this._actionManagers.splice(index, 1);
  26262. }
  26263. return index;
  26264. };
  26265. /**
  26266. * Removes the given effect layer from this scene.
  26267. * @param toRemove defines the effect layer to remove
  26268. * @returns the index of the removed effect layer
  26269. */
  26270. Scene.prototype.removeEffectLayer = function (toRemove) {
  26271. var index = this.effectLayers.indexOf(toRemove);
  26272. if (index !== -1) {
  26273. this.effectLayers.splice(index, 1);
  26274. }
  26275. return index;
  26276. };
  26277. /**
  26278. * Removes the given texture from this scene.
  26279. * @param toRemove The texture to remove
  26280. * @returns The index of the removed texture
  26281. */
  26282. Scene.prototype.removeTexture = function (toRemove) {
  26283. var index = this.textures.indexOf(toRemove);
  26284. if (index !== -1) {
  26285. this.textures.splice(index, 1);
  26286. }
  26287. return index;
  26288. };
  26289. /**
  26290. * Adds the given light to this scene
  26291. * @param newLight The light to add
  26292. */
  26293. Scene.prototype.addLight = function (newLight) {
  26294. this.lights.push(newLight);
  26295. this.sortLightsByPriority();
  26296. // Add light to all meshes (To support if the light is removed and then readded)
  26297. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26298. var mesh = _a[_i];
  26299. if (mesh._lightSources.indexOf(newLight) === -1) {
  26300. mesh._lightSources.push(newLight);
  26301. mesh._resyncLightSources();
  26302. }
  26303. }
  26304. this.onNewLightAddedObservable.notifyObservers(newLight);
  26305. };
  26306. /**
  26307. * Sorts the list list based on light priorities
  26308. */
  26309. Scene.prototype.sortLightsByPriority = function () {
  26310. if (this.requireLightSorting) {
  26311. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26312. }
  26313. };
  26314. /**
  26315. * Adds the given camera to this scene
  26316. * @param newCamera The camera to add
  26317. */
  26318. Scene.prototype.addCamera = function (newCamera) {
  26319. this.cameras.push(newCamera);
  26320. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26321. };
  26322. /**
  26323. * Adds the given skeleton to this scene
  26324. * @param newSkeleton The skeleton to add
  26325. */
  26326. Scene.prototype.addSkeleton = function (newSkeleton) {
  26327. this.skeletons.push(newSkeleton);
  26328. };
  26329. /**
  26330. * Adds the given particle system to this scene
  26331. * @param newParticleSystem The particle system to add
  26332. */
  26333. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26334. this.particleSystems.push(newParticleSystem);
  26335. };
  26336. /**
  26337. * Adds the given animation to this scene
  26338. * @param newAnimation The animation to add
  26339. */
  26340. Scene.prototype.addAnimation = function (newAnimation) {
  26341. this.animations.push(newAnimation);
  26342. };
  26343. /**
  26344. * Adds the given animation group to this scene.
  26345. * @param newAnimationGroup The animation group to add
  26346. */
  26347. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26348. this.animationGroups.push(newAnimationGroup);
  26349. };
  26350. /**
  26351. * Adds the given multi-material to this scene
  26352. * @param newMultiMaterial The multi-material to add
  26353. */
  26354. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26355. this.multiMaterials.push(newMultiMaterial);
  26356. };
  26357. /**
  26358. * Adds the given material to this scene
  26359. * @param newMaterial The material to add
  26360. */
  26361. Scene.prototype.addMaterial = function (newMaterial) {
  26362. this.materials.push(newMaterial);
  26363. };
  26364. /**
  26365. * Adds the given morph target to this scene
  26366. * @param newMorphTargetManager The morph target to add
  26367. */
  26368. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26369. this.morphTargetManagers.push(newMorphTargetManager);
  26370. };
  26371. /**
  26372. * Adds the given geometry to this scene
  26373. * @param newGeometry The geometry to add
  26374. */
  26375. Scene.prototype.addGeometry = function (newGeometry) {
  26376. this._geometries.push(newGeometry);
  26377. };
  26378. /**
  26379. * Adds the given lens flare system to this scene
  26380. * @param newLensFlareSystem The lens flare system to add
  26381. */
  26382. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  26383. this.lensFlareSystems.push(newLensFlareSystem);
  26384. };
  26385. /**
  26386. * Adds the given effect layer to this scene
  26387. * @param newEffectLayer defines the effect layer to add
  26388. */
  26389. Scene.prototype.addEffectLayer = function (newEffectLayer) {
  26390. this.effectLayers.push(newEffectLayer);
  26391. };
  26392. /**
  26393. * Adds the given action manager to this scene
  26394. * @param newActionManager The action manager to add
  26395. */
  26396. Scene.prototype.addActionManager = function (newActionManager) {
  26397. this._actionManagers.push(newActionManager);
  26398. };
  26399. /**
  26400. * Adds the given texture to this scene.
  26401. * @param newTexture The texture to add
  26402. */
  26403. Scene.prototype.addTexture = function (newTexture) {
  26404. this.textures.push(newTexture);
  26405. };
  26406. /**
  26407. * Switch active camera
  26408. * @param newCamera defines the new active camera
  26409. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26410. */
  26411. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26412. if (attachControl === void 0) { attachControl = true; }
  26413. var canvas = this._engine.getRenderingCanvas();
  26414. if (!canvas) {
  26415. return;
  26416. }
  26417. if (this.activeCamera) {
  26418. this.activeCamera.detachControl(canvas);
  26419. }
  26420. this.activeCamera = newCamera;
  26421. if (attachControl) {
  26422. newCamera.attachControl(canvas);
  26423. }
  26424. };
  26425. /**
  26426. * sets the active camera of the scene using its ID
  26427. * @param id defines the camera's ID
  26428. * @return the new active camera or null if none found.
  26429. */
  26430. Scene.prototype.setActiveCameraByID = function (id) {
  26431. var camera = this.getCameraByID(id);
  26432. if (camera) {
  26433. this.activeCamera = camera;
  26434. return camera;
  26435. }
  26436. return null;
  26437. };
  26438. /**
  26439. * sets the active camera of the scene using its name
  26440. * @param name defines the camera's name
  26441. * @returns the new active camera or null if none found.
  26442. */
  26443. Scene.prototype.setActiveCameraByName = function (name) {
  26444. var camera = this.getCameraByName(name);
  26445. if (camera) {
  26446. this.activeCamera = camera;
  26447. return camera;
  26448. }
  26449. return null;
  26450. };
  26451. /**
  26452. * get an animation group using its name
  26453. * @param name defines the material's name
  26454. * @return the animation group or null if none found.
  26455. */
  26456. Scene.prototype.getAnimationGroupByName = function (name) {
  26457. for (var index = 0; index < this.animationGroups.length; index++) {
  26458. if (this.animationGroups[index].name === name) {
  26459. return this.animationGroups[index];
  26460. }
  26461. }
  26462. return null;
  26463. };
  26464. /**
  26465. * get a material using its id
  26466. * @param id defines the material's ID
  26467. * @return the material or null if none found.
  26468. */
  26469. Scene.prototype.getMaterialByID = function (id) {
  26470. for (var index = 0; index < this.materials.length; index++) {
  26471. if (this.materials[index].id === id) {
  26472. return this.materials[index];
  26473. }
  26474. }
  26475. return null;
  26476. };
  26477. /**
  26478. * Gets a material using its name
  26479. * @param name defines the material's name
  26480. * @return the material or null if none found.
  26481. */
  26482. Scene.prototype.getMaterialByName = function (name) {
  26483. for (var index = 0; index < this.materials.length; index++) {
  26484. if (this.materials[index].name === name) {
  26485. return this.materials[index];
  26486. }
  26487. }
  26488. return null;
  26489. };
  26490. /**
  26491. * Gets a lens flare system using its name
  26492. * @param name defines the name to look for
  26493. * @returns the lens flare system or null if not found
  26494. */
  26495. Scene.prototype.getLensFlareSystemByName = function (name) {
  26496. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26497. if (this.lensFlareSystems[index].name === name) {
  26498. return this.lensFlareSystems[index];
  26499. }
  26500. }
  26501. return null;
  26502. };
  26503. /**
  26504. * Gets a lens flare system using its id
  26505. * @param id defines the id to look for
  26506. * @returns the lens flare system or null if not found
  26507. */
  26508. Scene.prototype.getLensFlareSystemByID = function (id) {
  26509. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26510. if (this.lensFlareSystems[index].id === id) {
  26511. return this.lensFlareSystems[index];
  26512. }
  26513. }
  26514. return null;
  26515. };
  26516. /**
  26517. * Gets a camera using its id
  26518. * @param id defines the id to look for
  26519. * @returns the camera or null if not found
  26520. */
  26521. Scene.prototype.getCameraByID = function (id) {
  26522. for (var index = 0; index < this.cameras.length; index++) {
  26523. if (this.cameras[index].id === id) {
  26524. return this.cameras[index];
  26525. }
  26526. }
  26527. return null;
  26528. };
  26529. /**
  26530. * Gets a camera using its unique id
  26531. * @param uniqueId defines the unique id to look for
  26532. * @returns the camera or null if not found
  26533. */
  26534. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  26535. for (var index = 0; index < this.cameras.length; index++) {
  26536. if (this.cameras[index].uniqueId === uniqueId) {
  26537. return this.cameras[index];
  26538. }
  26539. }
  26540. return null;
  26541. };
  26542. /**
  26543. * Gets a camera using its name
  26544. * @param name defines the camera's name
  26545. * @return the camera or null if none found.
  26546. */
  26547. Scene.prototype.getCameraByName = function (name) {
  26548. for (var index = 0; index < this.cameras.length; index++) {
  26549. if (this.cameras[index].name === name) {
  26550. return this.cameras[index];
  26551. }
  26552. }
  26553. return null;
  26554. };
  26555. /**
  26556. * Gets a bone using its id
  26557. * @param id defines the bone's id
  26558. * @return the bone or null if not found
  26559. */
  26560. Scene.prototype.getBoneByID = function (id) {
  26561. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26562. var skeleton = this.skeletons[skeletonIndex];
  26563. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26564. if (skeleton.bones[boneIndex].id === id) {
  26565. return skeleton.bones[boneIndex];
  26566. }
  26567. }
  26568. }
  26569. return null;
  26570. };
  26571. /**
  26572. * Gets a bone using its id
  26573. * @param name defines the bone's name
  26574. * @return the bone or null if not found
  26575. */
  26576. Scene.prototype.getBoneByName = function (name) {
  26577. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26578. var skeleton = this.skeletons[skeletonIndex];
  26579. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26580. if (skeleton.bones[boneIndex].name === name) {
  26581. return skeleton.bones[boneIndex];
  26582. }
  26583. }
  26584. }
  26585. return null;
  26586. };
  26587. /**
  26588. * Gets a light node using its name
  26589. * @param name defines the the light's name
  26590. * @return the light or null if none found.
  26591. */
  26592. Scene.prototype.getLightByName = function (name) {
  26593. for (var index = 0; index < this.lights.length; index++) {
  26594. if (this.lights[index].name === name) {
  26595. return this.lights[index];
  26596. }
  26597. }
  26598. return null;
  26599. };
  26600. /**
  26601. * Gets a light node using its id
  26602. * @param id defines the light's id
  26603. * @return the light or null if none found.
  26604. */
  26605. Scene.prototype.getLightByID = function (id) {
  26606. for (var index = 0; index < this.lights.length; index++) {
  26607. if (this.lights[index].id === id) {
  26608. return this.lights[index];
  26609. }
  26610. }
  26611. return null;
  26612. };
  26613. /**
  26614. * Gets a light node using its scene-generated unique ID
  26615. * @param uniqueId defines the light's unique id
  26616. * @return the light or null if none found.
  26617. */
  26618. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  26619. for (var index = 0; index < this.lights.length; index++) {
  26620. if (this.lights[index].uniqueId === uniqueId) {
  26621. return this.lights[index];
  26622. }
  26623. }
  26624. return null;
  26625. };
  26626. /**
  26627. * Gets a particle system by id
  26628. * @param id defines the particle system id
  26629. * @return the corresponding system or null if none found
  26630. */
  26631. Scene.prototype.getParticleSystemByID = function (id) {
  26632. for (var index = 0; index < this.particleSystems.length; index++) {
  26633. if (this.particleSystems[index].id === id) {
  26634. return this.particleSystems[index];
  26635. }
  26636. }
  26637. return null;
  26638. };
  26639. /**
  26640. * Gets a geometry using its ID
  26641. * @param id defines the geometry's id
  26642. * @return the geometry or null if none found.
  26643. */
  26644. Scene.prototype.getGeometryByID = function (id) {
  26645. for (var index = 0; index < this._geometries.length; index++) {
  26646. if (this._geometries[index].id === id) {
  26647. return this._geometries[index];
  26648. }
  26649. }
  26650. return null;
  26651. };
  26652. /**
  26653. * Add a new geometry to this scene
  26654. * @param geometry defines the geometry to be added to the scene.
  26655. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  26656. * @return a boolean defining if the geometry was added or not
  26657. */
  26658. Scene.prototype.pushGeometry = function (geometry, force) {
  26659. if (!force && this.getGeometryByID(geometry.id)) {
  26660. return false;
  26661. }
  26662. this._geometries.push(geometry);
  26663. //notify the collision coordinator
  26664. if (this.collisionCoordinator) {
  26665. this.collisionCoordinator.onGeometryAdded(geometry);
  26666. }
  26667. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  26668. return true;
  26669. };
  26670. /**
  26671. * Removes an existing geometry
  26672. * @param geometry defines the geometry to be removed from the scene
  26673. * @return a boolean defining if the geometry was removed or not
  26674. */
  26675. Scene.prototype.removeGeometry = function (geometry) {
  26676. var index = this._geometries.indexOf(geometry);
  26677. if (index > -1) {
  26678. this._geometries.splice(index, 1);
  26679. //notify the collision coordinator
  26680. if (this.collisionCoordinator) {
  26681. this.collisionCoordinator.onGeometryDeleted(geometry);
  26682. }
  26683. this.onGeometryRemovedObservable.notifyObservers(geometry);
  26684. return true;
  26685. }
  26686. return false;
  26687. };
  26688. /**
  26689. * Gets the list of geometries attached to the scene
  26690. * @returns an array of Geometry
  26691. */
  26692. Scene.prototype.getGeometries = function () {
  26693. return this._geometries;
  26694. };
  26695. /**
  26696. * Gets the first added mesh found of a given ID
  26697. * @param id defines the id to search for
  26698. * @return the mesh found or null if not found at all
  26699. */
  26700. Scene.prototype.getMeshByID = function (id) {
  26701. for (var index = 0; index < this.meshes.length; index++) {
  26702. if (this.meshes[index].id === id) {
  26703. return this.meshes[index];
  26704. }
  26705. }
  26706. return null;
  26707. };
  26708. /**
  26709. * Gets a list of meshes using their id
  26710. * @param id defines the id to search for
  26711. * @returns a list of meshes
  26712. */
  26713. Scene.prototype.getMeshesByID = function (id) {
  26714. return this.meshes.filter(function (m) {
  26715. return m.id === id;
  26716. });
  26717. };
  26718. /**
  26719. * Gets the first added transform node found of a given ID
  26720. * @param id defines the id to search for
  26721. * @return the found transform node or null if not found at all.
  26722. */
  26723. Scene.prototype.getTransformNodeByID = function (id) {
  26724. for (var index = 0; index < this.transformNodes.length; index++) {
  26725. if (this.transformNodes[index].id === id) {
  26726. return this.transformNodes[index];
  26727. }
  26728. }
  26729. return null;
  26730. };
  26731. /**
  26732. * Gets a list of transform nodes using their id
  26733. * @param id defines the id to search for
  26734. * @returns a list of transform nodes
  26735. */
  26736. Scene.prototype.getTransformNodesByID = function (id) {
  26737. return this.transformNodes.filter(function (m) {
  26738. return m.id === id;
  26739. });
  26740. };
  26741. /**
  26742. * Gets a mesh with its auto-generated unique id
  26743. * @param uniqueId defines the unique id to search for
  26744. * @return the found mesh or null if not found at all.
  26745. */
  26746. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  26747. for (var index = 0; index < this.meshes.length; index++) {
  26748. if (this.meshes[index].uniqueId === uniqueId) {
  26749. return this.meshes[index];
  26750. }
  26751. }
  26752. return null;
  26753. };
  26754. /**
  26755. * Gets a the last added mesh using a given id
  26756. * @param id defines the id to search for
  26757. * @return the found mesh or null if not found at all.
  26758. */
  26759. Scene.prototype.getLastMeshByID = function (id) {
  26760. for (var index = this.meshes.length - 1; index >= 0; index--) {
  26761. if (this.meshes[index].id === id) {
  26762. return this.meshes[index];
  26763. }
  26764. }
  26765. return null;
  26766. };
  26767. /**
  26768. * Gets a the last added node (Mesh, Camera, Light) using a given id
  26769. * @param id defines the id to search for
  26770. * @return the found node or null if not found at all
  26771. */
  26772. Scene.prototype.getLastEntryByID = function (id) {
  26773. var index;
  26774. for (index = this.meshes.length - 1; index >= 0; index--) {
  26775. if (this.meshes[index].id === id) {
  26776. return this.meshes[index];
  26777. }
  26778. }
  26779. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  26780. if (this.transformNodes[index].id === id) {
  26781. return this.transformNodes[index];
  26782. }
  26783. }
  26784. for (index = this.cameras.length - 1; index >= 0; index--) {
  26785. if (this.cameras[index].id === id) {
  26786. return this.cameras[index];
  26787. }
  26788. }
  26789. for (index = this.lights.length - 1; index >= 0; index--) {
  26790. if (this.lights[index].id === id) {
  26791. return this.lights[index];
  26792. }
  26793. }
  26794. return null;
  26795. };
  26796. /**
  26797. * Gets a node (Mesh, Camera, Light) using a given id
  26798. * @param id defines the id to search for
  26799. * @return the found node or null if not found at all
  26800. */
  26801. Scene.prototype.getNodeByID = function (id) {
  26802. var mesh = this.getMeshByID(id);
  26803. if (mesh) {
  26804. return mesh;
  26805. }
  26806. var light = this.getLightByID(id);
  26807. if (light) {
  26808. return light;
  26809. }
  26810. var camera = this.getCameraByID(id);
  26811. if (camera) {
  26812. return camera;
  26813. }
  26814. var bone = this.getBoneByID(id);
  26815. return bone;
  26816. };
  26817. /**
  26818. * Gets a node (Mesh, Camera, Light) using a given name
  26819. * @param name defines the name to search for
  26820. * @return the found node or null if not found at all.
  26821. */
  26822. Scene.prototype.getNodeByName = function (name) {
  26823. var mesh = this.getMeshByName(name);
  26824. if (mesh) {
  26825. return mesh;
  26826. }
  26827. var light = this.getLightByName(name);
  26828. if (light) {
  26829. return light;
  26830. }
  26831. var camera = this.getCameraByName(name);
  26832. if (camera) {
  26833. return camera;
  26834. }
  26835. var bone = this.getBoneByName(name);
  26836. return bone;
  26837. };
  26838. /**
  26839. * Gets a mesh using a given name
  26840. * @param name defines the name to search for
  26841. * @return the found mesh or null if not found at all.
  26842. */
  26843. Scene.prototype.getMeshByName = function (name) {
  26844. for (var index = 0; index < this.meshes.length; index++) {
  26845. if (this.meshes[index].name === name) {
  26846. return this.meshes[index];
  26847. }
  26848. }
  26849. return null;
  26850. };
  26851. /**
  26852. * Gets a transform node using a given name
  26853. * @param name defines the name to search for
  26854. * @return the found transform node or null if not found at all.
  26855. */
  26856. Scene.prototype.getTransformNodeByName = function (name) {
  26857. for (var index = 0; index < this.transformNodes.length; index++) {
  26858. if (this.transformNodes[index].name === name) {
  26859. return this.transformNodes[index];
  26860. }
  26861. }
  26862. return null;
  26863. };
  26864. /**
  26865. * Gets a sound using a given name
  26866. * @param name defines the name to search for
  26867. * @return the found sound or null if not found at all.
  26868. */
  26869. Scene.prototype.getSoundByName = function (name) {
  26870. var index;
  26871. if (BABYLON.AudioEngine) {
  26872. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  26873. if (this.mainSoundTrack.soundCollection[index].name === name) {
  26874. return this.mainSoundTrack.soundCollection[index];
  26875. }
  26876. }
  26877. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  26878. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  26879. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  26880. return this.soundTracks[sdIndex].soundCollection[index];
  26881. }
  26882. }
  26883. }
  26884. }
  26885. return null;
  26886. };
  26887. /**
  26888. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  26889. * @param id defines the id to search for
  26890. * @return the found skeleton or null if not found at all.
  26891. */
  26892. Scene.prototype.getLastSkeletonByID = function (id) {
  26893. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  26894. if (this.skeletons[index].id === id) {
  26895. return this.skeletons[index];
  26896. }
  26897. }
  26898. return null;
  26899. };
  26900. /**
  26901. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  26902. * @param id defines the id to search for
  26903. * @return the found skeleton or null if not found at all.
  26904. */
  26905. Scene.prototype.getSkeletonById = function (id) {
  26906. for (var index = 0; index < this.skeletons.length; index++) {
  26907. if (this.skeletons[index].id === id) {
  26908. return this.skeletons[index];
  26909. }
  26910. }
  26911. return null;
  26912. };
  26913. /**
  26914. * Gets a skeleton using a given name
  26915. * @param name defines the name to search for
  26916. * @return the found skeleton or null if not found at all.
  26917. */
  26918. Scene.prototype.getSkeletonByName = function (name) {
  26919. for (var index = 0; index < this.skeletons.length; index++) {
  26920. if (this.skeletons[index].name === name) {
  26921. return this.skeletons[index];
  26922. }
  26923. }
  26924. return null;
  26925. };
  26926. /**
  26927. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  26928. * @param id defines the id to search for
  26929. * @return the found morph target manager or null if not found at all.
  26930. */
  26931. Scene.prototype.getMorphTargetManagerById = function (id) {
  26932. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  26933. if (this.morphTargetManagers[index].uniqueId === id) {
  26934. return this.morphTargetManagers[index];
  26935. }
  26936. }
  26937. return null;
  26938. };
  26939. /**
  26940. * Gets a boolean indicating if the given mesh is active
  26941. * @param mesh defines the mesh to look for
  26942. * @returns true if the mesh is in the active list
  26943. */
  26944. Scene.prototype.isActiveMesh = function (mesh) {
  26945. return (this._activeMeshes.indexOf(mesh) !== -1);
  26946. };
  26947. /**
  26948. * Return a the first highlight layer of the scene with a given name.
  26949. * @param name The name of the highlight layer to look for.
  26950. * @return The highlight layer if found otherwise null.
  26951. */
  26952. Scene.prototype.getHighlightLayerByName = function (name) {
  26953. for (var index = 0; index < this.effectLayers.length; index++) {
  26954. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  26955. return this.effectLayers[index];
  26956. }
  26957. }
  26958. return null;
  26959. };
  26960. /**
  26961. * Return a the first highlight layer of the scene with a given name.
  26962. * @param name The name of the highlight layer to look for.
  26963. * @return The highlight layer if found otherwise null.
  26964. */
  26965. Scene.prototype.getGlowLayerByName = function (name) {
  26966. for (var index = 0; index < this.effectLayers.length; index++) {
  26967. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  26968. return this.effectLayers[index];
  26969. }
  26970. }
  26971. return null;
  26972. };
  26973. Object.defineProperty(Scene.prototype, "uid", {
  26974. /**
  26975. * Return a unique id as a string which can serve as an identifier for the scene
  26976. */
  26977. get: function () {
  26978. if (!this._uid) {
  26979. this._uid = BABYLON.Tools.RandomId();
  26980. }
  26981. return this._uid;
  26982. },
  26983. enumerable: true,
  26984. configurable: true
  26985. });
  26986. /**
  26987. * Add an externaly attached data from its key.
  26988. * This method call will fail and return false, if such key already exists.
  26989. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  26990. * @param key the unique key that identifies the data
  26991. * @param data the data object to associate to the key for this Engine instance
  26992. * @return true if no such key were already present and the data was added successfully, false otherwise
  26993. */
  26994. Scene.prototype.addExternalData = function (key, data) {
  26995. if (!this._externalData) {
  26996. this._externalData = new BABYLON.StringDictionary();
  26997. }
  26998. return this._externalData.add(key, data);
  26999. };
  27000. /**
  27001. * Get an externaly attached data from its key
  27002. * @param key the unique key that identifies the data
  27003. * @return the associated data, if present (can be null), or undefined if not present
  27004. */
  27005. Scene.prototype.getExternalData = function (key) {
  27006. if (!this._externalData) {
  27007. return null;
  27008. }
  27009. return this._externalData.get(key);
  27010. };
  27011. /**
  27012. * Get an externaly attached data from its key, create it using a factory if it's not already present
  27013. * @param key the unique key that identifies the data
  27014. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  27015. * @return the associated data, can be null if the factory returned null.
  27016. */
  27017. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  27018. if (!this._externalData) {
  27019. this._externalData = new BABYLON.StringDictionary();
  27020. }
  27021. return this._externalData.getOrAddWithFactory(key, factory);
  27022. };
  27023. /**
  27024. * Remove an externaly attached data from the Engine instance
  27025. * @param key the unique key that identifies the data
  27026. * @return true if the data was successfully removed, false if it doesn't exist
  27027. */
  27028. Scene.prototype.removeExternalData = function (key) {
  27029. return this._externalData.remove(key);
  27030. };
  27031. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  27032. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  27033. if (mesh.showSubMeshesBoundingBox) {
  27034. var boundingInfo = subMesh.getBoundingInfo();
  27035. if (boundingInfo !== null && boundingInfo !== undefined) {
  27036. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27037. }
  27038. }
  27039. var material = subMesh.getMaterial();
  27040. if (material !== null && material !== undefined) {
  27041. // Render targets
  27042. if (material.getRenderTargetTextures !== undefined) {
  27043. if (this._processedMaterials.indexOf(material) === -1) {
  27044. this._processedMaterials.push(material);
  27045. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27046. }
  27047. }
  27048. // Dispatch
  27049. this._activeIndices.addCount(subMesh.indexCount, false);
  27050. this._renderingManager.dispatch(subMesh, mesh, material);
  27051. }
  27052. }
  27053. };
  27054. /**
  27055. * Clear the processed materials smart array preventing retention point in material dispose.
  27056. */
  27057. Scene.prototype.freeProcessedMaterials = function () {
  27058. this._processedMaterials.dispose();
  27059. };
  27060. /**
  27061. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27062. */
  27063. Scene.prototype.freeActiveMeshes = function () {
  27064. this._activeMeshes.dispose();
  27065. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27066. this.activeCamera._activeMeshes.dispose();
  27067. }
  27068. if (this.activeCameras) {
  27069. for (var i = 0; i < this.activeCameras.length; i++) {
  27070. var activeCamera = this.activeCameras[i];
  27071. if (activeCamera && activeCamera._activeMeshes) {
  27072. activeCamera._activeMeshes.dispose();
  27073. }
  27074. }
  27075. }
  27076. };
  27077. /**
  27078. * Clear the info related to rendering groups preventing retention points during dispose.
  27079. */
  27080. Scene.prototype.freeRenderingGroups = function () {
  27081. if (this._renderingManager) {
  27082. this._renderingManager.freeRenderingGroups();
  27083. }
  27084. if (this.textures) {
  27085. for (var i = 0; i < this.textures.length; i++) {
  27086. var texture = this.textures[i];
  27087. if (texture && texture.renderList) {
  27088. texture.freeRenderingGroups();
  27089. }
  27090. }
  27091. }
  27092. };
  27093. /** @hidden */
  27094. Scene.prototype._isInIntermediateRendering = function () {
  27095. return this._intermediateRendering;
  27096. };
  27097. /**
  27098. * Defines the current active mesh candidate provider
  27099. * @param provider defines the provider to use
  27100. */
  27101. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  27102. this._activeMeshCandidateProvider = provider;
  27103. };
  27104. /**
  27105. * Gets the current active mesh candidate provider
  27106. * @returns the current active mesh candidate provider
  27107. */
  27108. Scene.prototype.getActiveMeshCandidateProvider = function () {
  27109. return this._activeMeshCandidateProvider;
  27110. };
  27111. /**
  27112. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27113. * @returns the current scene
  27114. */
  27115. Scene.prototype.freezeActiveMeshes = function () {
  27116. if (!this.activeCamera) {
  27117. return this;
  27118. }
  27119. if (!this._frustumPlanes) {
  27120. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27121. }
  27122. this._evaluateActiveMeshes();
  27123. this._activeMeshesFrozen = true;
  27124. return this;
  27125. };
  27126. /**
  27127. * Use this function to restart evaluating active meshes on every frame
  27128. * @returns the current scene
  27129. */
  27130. Scene.prototype.unfreezeActiveMeshes = function () {
  27131. this._activeMeshesFrozen = false;
  27132. return this;
  27133. };
  27134. Scene.prototype._evaluateActiveMeshes = function () {
  27135. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27136. return;
  27137. }
  27138. if (!this.activeCamera) {
  27139. return;
  27140. }
  27141. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27142. this.activeCamera._activeMeshes.reset();
  27143. this._activeMeshes.reset();
  27144. this._renderingManager.reset();
  27145. this._processedMaterials.reset();
  27146. this._activeParticleSystems.reset();
  27147. this._activeSkeletons.reset();
  27148. this._softwareSkinnedMeshes.reset();
  27149. if (this._boundingBoxRenderer) {
  27150. this._boundingBoxRenderer.reset();
  27151. }
  27152. // Meshes
  27153. var meshes;
  27154. var len;
  27155. var checkIsEnabled = true;
  27156. // Determine mesh candidates
  27157. if (this._activeMeshCandidateProvider !== undefined) {
  27158. // Use _activeMeshCandidateProvider
  27159. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  27160. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  27161. if (meshes !== undefined) {
  27162. len = meshes.length;
  27163. }
  27164. else {
  27165. len = 0;
  27166. }
  27167. }
  27168. else if (this._selectionOctree !== undefined) {
  27169. // Octree
  27170. var selection = this._selectionOctree.select(this._frustumPlanes);
  27171. meshes = selection.data;
  27172. len = selection.length;
  27173. }
  27174. else {
  27175. // Full scene traversal
  27176. len = this.meshes.length;
  27177. meshes = this.meshes;
  27178. }
  27179. // Check each mesh
  27180. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  27181. mesh = meshes[meshIndex];
  27182. if (mesh.isBlocked) {
  27183. continue;
  27184. }
  27185. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27186. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  27187. continue;
  27188. }
  27189. mesh.computeWorldMatrix();
  27190. // Intersections
  27191. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  27192. this._meshesForIntersections.pushNoDuplicate(mesh);
  27193. }
  27194. // Switch to current LOD
  27195. meshLOD = mesh.getLOD(this.activeCamera);
  27196. if (meshLOD === undefined || meshLOD === null) {
  27197. continue;
  27198. }
  27199. mesh._preActivate();
  27200. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  27201. this._activeMeshes.push(mesh);
  27202. this.activeCamera._activeMeshes.push(mesh);
  27203. mesh._activate(this._renderId);
  27204. if (meshLOD !== mesh) {
  27205. meshLOD._activate(this._renderId);
  27206. }
  27207. this._activeMesh(mesh, meshLOD);
  27208. }
  27209. }
  27210. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27211. // Particle systems
  27212. if (this.particlesEnabled) {
  27213. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27214. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27215. var particleSystem = this.particleSystems[particleIndex];
  27216. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27217. continue;
  27218. }
  27219. var emitter = particleSystem.emitter;
  27220. if (!emitter.position || emitter.isEnabled()) {
  27221. this._activeParticleSystems.push(particleSystem);
  27222. particleSystem.animate();
  27223. this._renderingManager.dispatchParticles(particleSystem);
  27224. }
  27225. }
  27226. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27227. }
  27228. };
  27229. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27230. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27231. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27232. mesh.skeleton.prepare();
  27233. }
  27234. if (!mesh.computeBonesUsingShaders) {
  27235. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27236. }
  27237. }
  27238. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  27239. var boundingInfo = sourceMesh.getBoundingInfo();
  27240. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27241. }
  27242. if (mesh !== undefined && mesh !== null
  27243. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27244. // Submeshes Octrees
  27245. var len;
  27246. var subMeshes;
  27247. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  27248. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  27249. len = intersections.length;
  27250. subMeshes = intersections.data;
  27251. }
  27252. else {
  27253. subMeshes = mesh.subMeshes;
  27254. len = subMeshes.length;
  27255. }
  27256. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  27257. subMesh = subMeshes[subIndex];
  27258. this._evaluateSubMesh(subMesh, mesh);
  27259. }
  27260. }
  27261. };
  27262. /**
  27263. * Update the transform matrix to update from the current active camera
  27264. * @param force defines a boolean used to force the update even if cache is up to date
  27265. */
  27266. Scene.prototype.updateTransformMatrix = function (force) {
  27267. if (!this.activeCamera) {
  27268. return;
  27269. }
  27270. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27271. };
  27272. /**
  27273. * 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)
  27274. * @param alternateCamera defines the camera to use
  27275. */
  27276. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27277. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27278. };
  27279. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27280. if (camera && camera._skipRendering) {
  27281. return;
  27282. }
  27283. var engine = this._engine;
  27284. this.activeCamera = camera;
  27285. if (!this.activeCamera)
  27286. throw new Error("Active camera not set");
  27287. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  27288. // Viewport
  27289. engine.setViewport(this.activeCamera.viewport);
  27290. // Camera
  27291. this.resetCachedMaterial();
  27292. this._renderId++;
  27293. this.updateTransformMatrix();
  27294. if (camera._alternateCamera) {
  27295. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27296. this._alternateRendering = true;
  27297. }
  27298. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27299. // Meshes
  27300. this._evaluateActiveMeshes();
  27301. // Software skinning
  27302. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27303. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27304. mesh.applySkeleton(mesh.skeleton);
  27305. }
  27306. // Render targets
  27307. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27308. var needsRestoreFrameBuffer = false;
  27309. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27310. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27311. }
  27312. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27313. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27314. }
  27315. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  27316. this._intermediateRendering = true;
  27317. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27318. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27319. var renderTarget = this._renderTargets.data[renderIndex];
  27320. if (renderTarget._shouldRender()) {
  27321. this._renderId++;
  27322. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27323. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27324. }
  27325. }
  27326. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27327. this._intermediateRendering = false;
  27328. this._renderId++;
  27329. needsRestoreFrameBuffer = true; // Restore back buffer
  27330. }
  27331. // Render EffecttLayer Texture
  27332. var stencilState = this._engine.getStencilBuffer();
  27333. var renderEffects = false;
  27334. var needStencil = false;
  27335. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  27336. this._intermediateRendering = true;
  27337. for (var i = 0; i < this.effectLayers.length; i++) {
  27338. var effectLayer = this.effectLayers[i];
  27339. if (effectLayer.shouldRender() &&
  27340. (!effectLayer.camera ||
  27341. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  27342. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  27343. renderEffects = true;
  27344. needStencil = needStencil || effectLayer.needStencil();
  27345. var renderTarget = effectLayer._mainTexture;
  27346. if (renderTarget._shouldRender()) {
  27347. this._renderId++;
  27348. renderTarget.render(false, false);
  27349. needsRestoreFrameBuffer = true;
  27350. }
  27351. }
  27352. }
  27353. this._intermediateRendering = false;
  27354. this._renderId++;
  27355. }
  27356. if (needsRestoreFrameBuffer) {
  27357. engine.restoreDefaultFramebuffer(); // Restore back buffer
  27358. }
  27359. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27360. // Prepare Frame
  27361. this.postProcessManager._prepareFrame();
  27362. // Backgrounds
  27363. var layerIndex;
  27364. var layer;
  27365. if (this.layers.length) {
  27366. engine.setDepthBuffer(false);
  27367. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27368. layer = this.layers[layerIndex];
  27369. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27370. layer.render();
  27371. }
  27372. }
  27373. engine.setDepthBuffer(true);
  27374. }
  27375. // Activate effect Layer stencil
  27376. if (needStencil) {
  27377. this._engine.setStencilBuffer(true);
  27378. }
  27379. // Render
  27380. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27381. this._renderingManager.render(null, null, true, true);
  27382. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27383. // Restore effect Layer stencil
  27384. if (needStencil) {
  27385. this._engine.setStencilBuffer(stencilState);
  27386. }
  27387. // Bounding boxes
  27388. if (this._boundingBoxRenderer) {
  27389. this._boundingBoxRenderer.render();
  27390. }
  27391. // Lens flares
  27392. if (this.lensFlaresEnabled) {
  27393. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27394. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  27395. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  27396. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  27397. lensFlareSystem.render();
  27398. }
  27399. }
  27400. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27401. }
  27402. // Effect Layer
  27403. if (renderEffects) {
  27404. engine.setDepthBuffer(false);
  27405. for (var i = 0; i < this.effectLayers.length; i++) {
  27406. if (this.effectLayers[i].shouldRender()) {
  27407. this.effectLayers[i].render();
  27408. }
  27409. }
  27410. engine.setDepthBuffer(true);
  27411. }
  27412. // Foregrounds
  27413. if (this.layers.length) {
  27414. engine.setDepthBuffer(false);
  27415. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27416. layer = this.layers[layerIndex];
  27417. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27418. layer.render();
  27419. }
  27420. }
  27421. engine.setDepthBuffer(true);
  27422. }
  27423. // Finalize frame
  27424. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27425. // Reset some special arrays
  27426. this._renderTargets.reset();
  27427. this._alternateRendering = false;
  27428. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27429. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  27430. };
  27431. Scene.prototype._processSubCameras = function (camera) {
  27432. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27433. this._renderForCamera(camera);
  27434. return;
  27435. }
  27436. // rig cameras
  27437. for (var index = 0; index < camera._rigCameras.length; index++) {
  27438. this._renderForCamera(camera._rigCameras[index], camera);
  27439. }
  27440. this.activeCamera = camera;
  27441. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27442. };
  27443. Scene.prototype._checkIntersections = function () {
  27444. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27445. var sourceMesh = this._meshesForIntersections.data[index];
  27446. if (!sourceMesh.actionManager) {
  27447. continue;
  27448. }
  27449. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27450. var action = sourceMesh.actionManager.actions[actionIndex];
  27451. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27452. var parameters = action.getTriggerParameter();
  27453. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27454. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27455. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27456. if (areIntersecting && currentIntersectionInProgress === -1) {
  27457. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27458. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27459. sourceMesh._intersectionsInProgress.push(otherMesh);
  27460. }
  27461. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27462. sourceMesh._intersectionsInProgress.push(otherMesh);
  27463. }
  27464. }
  27465. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27466. //They intersected, and now they don't.
  27467. //is this trigger an exit trigger? execute an event.
  27468. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27469. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27470. }
  27471. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27472. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27473. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27474. return otherMesh === parameterMesh;
  27475. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27476. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27477. }
  27478. }
  27479. }
  27480. }
  27481. }
  27482. };
  27483. /**
  27484. * Render the scene
  27485. */
  27486. Scene.prototype.render = function () {
  27487. if (this.isDisposed) {
  27488. return;
  27489. }
  27490. this._activeParticles.fetchNewFrame();
  27491. this._totalVertices.fetchNewFrame();
  27492. this._activeIndices.fetchNewFrame();
  27493. this._activeBones.fetchNewFrame();
  27494. this._meshesForIntersections.reset();
  27495. this.resetCachedMaterial();
  27496. this.onBeforeAnimationsObservable.notifyObservers(this);
  27497. // Actions
  27498. if (this.actionManager) {
  27499. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27500. }
  27501. //Simplification Queue
  27502. if (this.simplificationQueue && !this.simplificationQueue.running) {
  27503. this.simplificationQueue.executeNext();
  27504. }
  27505. if (this._engine.isDeterministicLockStep()) {
  27506. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27507. var defaultFPS = (60.0 / 1000.0);
  27508. var defaultFrameTime = 1000 / 60; // frame time in MS
  27509. if (this._physicsEngine) {
  27510. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  27511. }
  27512. var stepsTaken = 0;
  27513. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27514. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27515. internalSteps = Math.min(internalSteps, maxSubSteps);
  27516. do {
  27517. this.onBeforeStepObservable.notifyObservers(this);
  27518. // Animations
  27519. this._animationRatio = defaultFrameTime * defaultFPS;
  27520. this._animate();
  27521. this.onAfterAnimationsObservable.notifyObservers(this);
  27522. // Physics
  27523. if (this._physicsEngine) {
  27524. this.onBeforePhysicsObservable.notifyObservers(this);
  27525. this._physicsEngine._step(defaultFrameTime / 1000);
  27526. this.onAfterPhysicsObservable.notifyObservers(this);
  27527. }
  27528. this.onAfterStepObservable.notifyObservers(this);
  27529. this._currentStepId++;
  27530. stepsTaken++;
  27531. deltaTime -= defaultFrameTime;
  27532. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27533. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27534. }
  27535. else {
  27536. // Animations
  27537. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27538. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27539. this._animate();
  27540. this.onAfterAnimationsObservable.notifyObservers(this);
  27541. // Physics
  27542. if (this._physicsEngine) {
  27543. this.onBeforePhysicsObservable.notifyObservers(this);
  27544. this._physicsEngine._step(deltaTime / 1000.0);
  27545. this.onAfterPhysicsObservable.notifyObservers(this);
  27546. }
  27547. }
  27548. // update gamepad manager
  27549. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  27550. this._gamepadManager._checkGamepadsStatus();
  27551. }
  27552. // Update Cameras
  27553. if (this.activeCameras.length > 0) {
  27554. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27555. var camera = this.activeCameras[cameraIndex];
  27556. camera.update();
  27557. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27558. // rig cameras
  27559. for (var index = 0; index < camera._rigCameras.length; index++) {
  27560. camera._rigCameras[index].update();
  27561. }
  27562. }
  27563. }
  27564. }
  27565. else if (this.activeCamera) {
  27566. this.activeCamera.update();
  27567. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27568. // rig cameras
  27569. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27570. this.activeCamera._rigCameras[index].update();
  27571. }
  27572. }
  27573. }
  27574. // Before render
  27575. this.onBeforeRenderObservable.notifyObservers(this);
  27576. // Customs render targets
  27577. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27578. var engine = this.getEngine();
  27579. var currentActiveCamera = this.activeCamera;
  27580. if (this.renderTargetsEnabled) {
  27581. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27582. this._intermediateRendering = true;
  27583. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  27584. var renderTarget = this.customRenderTargets[customIndex];
  27585. if (renderTarget._shouldRender()) {
  27586. this._renderId++;
  27587. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  27588. if (!this.activeCamera)
  27589. throw new Error("Active camera not set");
  27590. // Viewport
  27591. engine.setViewport(this.activeCamera.viewport);
  27592. // Camera
  27593. this.updateTransformMatrix();
  27594. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  27595. }
  27596. }
  27597. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27598. this._intermediateRendering = false;
  27599. this._renderId++;
  27600. }
  27601. // Restore back buffer
  27602. if (this.customRenderTargets.length > 0) {
  27603. engine.restoreDefaultFramebuffer();
  27604. }
  27605. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27606. this.activeCamera = currentActiveCamera;
  27607. // Procedural textures
  27608. if (this.proceduralTexturesEnabled) {
  27609. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27610. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  27611. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  27612. if (proceduralTexture._shouldRender()) {
  27613. proceduralTexture.render();
  27614. }
  27615. }
  27616. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27617. }
  27618. // Clear
  27619. if (this.autoClearDepthAndStencil || this.autoClear) {
  27620. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  27621. }
  27622. // Shadows
  27623. if (this.shadowsEnabled) {
  27624. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  27625. var light = this.lights[lightIndex];
  27626. var shadowGenerator = light.getShadowGenerator();
  27627. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  27628. var shadowMap = (shadowGenerator.getShadowMap());
  27629. if (this.textures.indexOf(shadowMap) !== -1) {
  27630. this._renderTargets.push(shadowMap);
  27631. }
  27632. }
  27633. }
  27634. }
  27635. // Depth renderer
  27636. for (var key in this._depthRenderer) {
  27637. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  27638. }
  27639. // Geometry renderer
  27640. if (this._geometryBufferRenderer) {
  27641. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  27642. }
  27643. // RenderPipeline
  27644. if (this._postProcessRenderPipelineManager) {
  27645. this._postProcessRenderPipelineManager.update();
  27646. }
  27647. // Multi-cameras?
  27648. if (this.activeCameras.length > 0) {
  27649. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27650. if (cameraIndex > 0) {
  27651. this._engine.clear(null, false, true, true);
  27652. }
  27653. this._processSubCameras(this.activeCameras[cameraIndex]);
  27654. }
  27655. }
  27656. else {
  27657. if (!this.activeCamera) {
  27658. throw new Error("No camera defined");
  27659. }
  27660. this._processSubCameras(this.activeCamera);
  27661. }
  27662. // Intersection checks
  27663. this._checkIntersections();
  27664. // Update the audio listener attached to the camera
  27665. if (BABYLON.AudioEngine) {
  27666. this._updateAudioParameters();
  27667. }
  27668. // After render
  27669. if (this.afterRender) {
  27670. this.afterRender();
  27671. }
  27672. this.onAfterRenderObservable.notifyObservers(this);
  27673. // Cleaning
  27674. for (var index = 0; index < this._toBeDisposed.length; index++) {
  27675. var data = this._toBeDisposed.data[index];
  27676. if (data) {
  27677. data.dispose();
  27678. }
  27679. this._toBeDisposed[index] = null;
  27680. }
  27681. this._toBeDisposed.reset();
  27682. if (this.dumpNextRenderTargets) {
  27683. this.dumpNextRenderTargets = false;
  27684. }
  27685. this._activeBones.addCount(0, true);
  27686. this._activeIndices.addCount(0, true);
  27687. this._activeParticles.addCount(0, true);
  27688. };
  27689. Scene.prototype._updateAudioParameters = function () {
  27690. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  27691. return;
  27692. }
  27693. var listeningCamera;
  27694. var audioEngine = BABYLON.Engine.audioEngine;
  27695. if (this.activeCameras.length > 0) {
  27696. listeningCamera = this.activeCameras[0];
  27697. }
  27698. else {
  27699. listeningCamera = this.activeCamera;
  27700. }
  27701. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  27702. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  27703. // for VR cameras
  27704. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  27705. listeningCamera = listeningCamera.rigCameras[0];
  27706. }
  27707. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  27708. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  27709. cameraDirection.normalize();
  27710. // To avoid some errors on GearVR
  27711. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  27712. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  27713. }
  27714. var i;
  27715. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27716. var sound = this.mainSoundTrack.soundCollection[i];
  27717. if (sound.useCustomAttenuation) {
  27718. sound.updateDistanceFromListener();
  27719. }
  27720. }
  27721. for (i = 0; i < this.soundTracks.length; i++) {
  27722. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27723. sound = this.soundTracks[i].soundCollection[j];
  27724. if (sound.useCustomAttenuation) {
  27725. sound.updateDistanceFromListener();
  27726. }
  27727. }
  27728. }
  27729. }
  27730. };
  27731. Object.defineProperty(Scene.prototype, "audioEnabled", {
  27732. // Audio
  27733. /**
  27734. * Gets or sets if audio support is enabled
  27735. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27736. */
  27737. get: function () {
  27738. return this._audioEnabled;
  27739. },
  27740. set: function (value) {
  27741. this._audioEnabled = value;
  27742. if (BABYLON.AudioEngine) {
  27743. if (this._audioEnabled) {
  27744. this._enableAudio();
  27745. }
  27746. else {
  27747. this._disableAudio();
  27748. }
  27749. }
  27750. },
  27751. enumerable: true,
  27752. configurable: true
  27753. });
  27754. Scene.prototype._disableAudio = function () {
  27755. var i;
  27756. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27757. this.mainSoundTrack.soundCollection[i].pause();
  27758. }
  27759. for (i = 0; i < this.soundTracks.length; i++) {
  27760. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27761. this.soundTracks[i].soundCollection[j].pause();
  27762. }
  27763. }
  27764. };
  27765. Scene.prototype._enableAudio = function () {
  27766. var i;
  27767. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27768. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  27769. this.mainSoundTrack.soundCollection[i].play();
  27770. }
  27771. }
  27772. for (i = 0; i < this.soundTracks.length; i++) {
  27773. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27774. if (this.soundTracks[i].soundCollection[j].isPaused) {
  27775. this.soundTracks[i].soundCollection[j].play();
  27776. }
  27777. }
  27778. }
  27779. };
  27780. Object.defineProperty(Scene.prototype, "headphone", {
  27781. /**
  27782. * Gets or sets if audio will be output to headphones
  27783. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27784. */
  27785. get: function () {
  27786. return this._headphone;
  27787. },
  27788. set: function (value) {
  27789. this._headphone = value;
  27790. if (BABYLON.AudioEngine) {
  27791. if (this._headphone) {
  27792. this._switchAudioModeForHeadphones();
  27793. }
  27794. else {
  27795. this._switchAudioModeForNormalSpeakers();
  27796. }
  27797. }
  27798. },
  27799. enumerable: true,
  27800. configurable: true
  27801. });
  27802. Scene.prototype._switchAudioModeForHeadphones = function () {
  27803. this.mainSoundTrack.switchPanningModelToHRTF();
  27804. for (var i = 0; i < this.soundTracks.length; i++) {
  27805. this.soundTracks[i].switchPanningModelToHRTF();
  27806. }
  27807. };
  27808. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  27809. this.mainSoundTrack.switchPanningModelToEqualPower();
  27810. for (var i = 0; i < this.soundTracks.length; i++) {
  27811. this.soundTracks[i].switchPanningModelToEqualPower();
  27812. }
  27813. };
  27814. /**
  27815. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  27816. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  27817. * @returns the created depth renderer
  27818. */
  27819. Scene.prototype.enableDepthRenderer = function (camera) {
  27820. camera = camera || this.activeCamera;
  27821. if (!camera) {
  27822. throw "No camera available to enable depth renderer";
  27823. }
  27824. if (!this._depthRenderer[camera.id]) {
  27825. var textureType = 0;
  27826. if (this._engine.getCaps().textureHalfFloatRender) {
  27827. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  27828. }
  27829. else if (this._engine.getCaps().textureFloatRender) {
  27830. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  27831. }
  27832. else {
  27833. throw "Depth renderer does not support int texture type";
  27834. }
  27835. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  27836. }
  27837. return this._depthRenderer[camera.id];
  27838. };
  27839. /**
  27840. * Disables a depth renderer for a given camera
  27841. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  27842. */
  27843. Scene.prototype.disableDepthRenderer = function (camera) {
  27844. camera = camera || this.activeCamera;
  27845. if (!camera || !this._depthRenderer[camera.id]) {
  27846. return;
  27847. }
  27848. this._depthRenderer[camera.id].dispose();
  27849. delete this._depthRenderer[camera.id];
  27850. };
  27851. /**
  27852. * Enables a GeometryBufferRender and associates it with the scene
  27853. * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)
  27854. * @returns the GeometryBufferRenderer
  27855. */
  27856. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  27857. if (ratio === void 0) { ratio = 1; }
  27858. if (this._geometryBufferRenderer) {
  27859. return this._geometryBufferRenderer;
  27860. }
  27861. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  27862. if (!this._geometryBufferRenderer.isSupported) {
  27863. this._geometryBufferRenderer = null;
  27864. }
  27865. return this._geometryBufferRenderer;
  27866. };
  27867. /**
  27868. * Disables the GeometryBufferRender associated with the scene
  27869. */
  27870. Scene.prototype.disableGeometryBufferRenderer = function () {
  27871. if (!this._geometryBufferRenderer) {
  27872. return;
  27873. }
  27874. this._geometryBufferRenderer.dispose();
  27875. this._geometryBufferRenderer = null;
  27876. };
  27877. /**
  27878. * Freeze all materials
  27879. * A frozen material will not be updatable but should be faster to render
  27880. */
  27881. Scene.prototype.freezeMaterials = function () {
  27882. for (var i = 0; i < this.materials.length; i++) {
  27883. this.materials[i].freeze();
  27884. }
  27885. };
  27886. /**
  27887. * Unfreeze all materials
  27888. * A frozen material will not be updatable but should be faster to render
  27889. */
  27890. Scene.prototype.unfreezeMaterials = function () {
  27891. for (var i = 0; i < this.materials.length; i++) {
  27892. this.materials[i].unfreeze();
  27893. }
  27894. };
  27895. /**
  27896. * Releases all held ressources
  27897. */
  27898. Scene.prototype.dispose = function () {
  27899. this.beforeRender = null;
  27900. this.afterRender = null;
  27901. this.skeletons = [];
  27902. this.morphTargetManagers = [];
  27903. this.importedMeshesFiles = new Array();
  27904. this.stopAllAnimations();
  27905. this.resetCachedMaterial();
  27906. for (var key in this._depthRenderer) {
  27907. this._depthRenderer[key].dispose();
  27908. }
  27909. if (this._gamepadManager) {
  27910. this._gamepadManager.dispose();
  27911. this._gamepadManager = null;
  27912. }
  27913. // Smart arrays
  27914. if (this.activeCamera) {
  27915. this.activeCamera._activeMeshes.dispose();
  27916. this.activeCamera = null;
  27917. }
  27918. this._activeMeshes.dispose();
  27919. this._renderingManager.dispose();
  27920. this._processedMaterials.dispose();
  27921. this._activeParticleSystems.dispose();
  27922. this._activeSkeletons.dispose();
  27923. this._softwareSkinnedMeshes.dispose();
  27924. this._renderTargets.dispose();
  27925. this._registeredForLateAnimationBindings.dispose();
  27926. if (this._boundingBoxRenderer) {
  27927. this._boundingBoxRenderer.dispose();
  27928. }
  27929. this._meshesForIntersections.dispose();
  27930. this._toBeDisposed.dispose();
  27931. // Abort active requests
  27932. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  27933. var request = _a[_i];
  27934. request.abort();
  27935. }
  27936. // Debug layer
  27937. if (this._debugLayer) {
  27938. this._debugLayer.hide();
  27939. }
  27940. // Events
  27941. this.onDisposeObservable.notifyObservers(this);
  27942. this.onDisposeObservable.clear();
  27943. this.onBeforeRenderObservable.clear();
  27944. this.onAfterRenderObservable.clear();
  27945. this.onBeforeRenderTargetsRenderObservable.clear();
  27946. this.onAfterRenderTargetsRenderObservable.clear();
  27947. this.onAfterStepObservable.clear();
  27948. this.onBeforeStepObservable.clear();
  27949. this.onBeforeActiveMeshesEvaluationObservable.clear();
  27950. this.onAfterActiveMeshesEvaluationObservable.clear();
  27951. this.onBeforeParticlesRenderingObservable.clear();
  27952. this.onAfterParticlesRenderingObservable.clear();
  27953. this.onBeforeSpritesRenderingObservable.clear();
  27954. this.onAfterSpritesRenderingObservable.clear();
  27955. this.onBeforeDrawPhaseObservable.clear();
  27956. this.onAfterDrawPhaseObservable.clear();
  27957. this.onBeforePhysicsObservable.clear();
  27958. this.onAfterPhysicsObservable.clear();
  27959. this.onBeforeAnimationsObservable.clear();
  27960. this.onAfterAnimationsObservable.clear();
  27961. this.onDataLoadedObservable.clear();
  27962. this.detachControl();
  27963. // Release sounds & sounds tracks
  27964. if (BABYLON.AudioEngine) {
  27965. this.disposeSounds();
  27966. }
  27967. // VR Helper
  27968. if (this.VRHelper) {
  27969. this.VRHelper.dispose();
  27970. }
  27971. // Detach cameras
  27972. var canvas = this._engine.getRenderingCanvas();
  27973. if (canvas) {
  27974. var index;
  27975. for (index = 0; index < this.cameras.length; index++) {
  27976. this.cameras[index].detachControl(canvas);
  27977. }
  27978. }
  27979. // Release animation groups
  27980. while (this.animationGroups.length) {
  27981. this.animationGroups[0].dispose();
  27982. }
  27983. // Release lights
  27984. while (this.lights.length) {
  27985. this.lights[0].dispose();
  27986. }
  27987. // Release meshes
  27988. while (this.meshes.length) {
  27989. this.meshes[0].dispose(true);
  27990. }
  27991. while (this.transformNodes.length) {
  27992. this.removeTransformNode(this.transformNodes[0]);
  27993. }
  27994. // Release cameras
  27995. while (this.cameras.length) {
  27996. this.cameras[0].dispose();
  27997. }
  27998. // Release materials
  27999. if (this.defaultMaterial) {
  28000. this.defaultMaterial.dispose();
  28001. }
  28002. while (this.multiMaterials.length) {
  28003. this.multiMaterials[0].dispose();
  28004. }
  28005. while (this.materials.length) {
  28006. this.materials[0].dispose();
  28007. }
  28008. // Release particles
  28009. while (this.particleSystems.length) {
  28010. this.particleSystems[0].dispose();
  28011. }
  28012. // Release sprites
  28013. while (this.spriteManagers.length) {
  28014. this.spriteManagers[0].dispose();
  28015. }
  28016. // Release postProcesses
  28017. while (this.postProcesses.length) {
  28018. this.postProcesses[0].dispose();
  28019. }
  28020. // Release layers
  28021. while (this.layers.length) {
  28022. this.layers[0].dispose();
  28023. }
  28024. while (this.effectLayers.length) {
  28025. this.effectLayers[0].dispose();
  28026. }
  28027. // Release textures
  28028. while (this.textures.length) {
  28029. this.textures[0].dispose();
  28030. }
  28031. // Release UBO
  28032. this._sceneUbo.dispose();
  28033. if (this._alternateSceneUbo) {
  28034. this._alternateSceneUbo.dispose();
  28035. }
  28036. // Post-processes
  28037. this.postProcessManager.dispose();
  28038. if (this._postProcessRenderPipelineManager) {
  28039. this._postProcessRenderPipelineManager.dispose();
  28040. }
  28041. // Physics
  28042. if (this._physicsEngine) {
  28043. this.disablePhysicsEngine();
  28044. }
  28045. // Remove from engine
  28046. index = this._engine.scenes.indexOf(this);
  28047. if (index > -1) {
  28048. this._engine.scenes.splice(index, 1);
  28049. }
  28050. this._engine.wipeCaches(true);
  28051. this._isDisposed = true;
  28052. };
  28053. Object.defineProperty(Scene.prototype, "isDisposed", {
  28054. /**
  28055. * Gets if the scene is already disposed
  28056. */
  28057. get: function () {
  28058. return this._isDisposed;
  28059. },
  28060. enumerable: true,
  28061. configurable: true
  28062. });
  28063. /**
  28064. * Releases sounds & soundtracks
  28065. */
  28066. Scene.prototype.disposeSounds = function () {
  28067. if (!this._mainSoundTrack) {
  28068. return;
  28069. }
  28070. this.mainSoundTrack.dispose();
  28071. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  28072. this.soundTracks[scIndex].dispose();
  28073. }
  28074. };
  28075. // Octrees
  28076. /**
  28077. * Get the world extend vectors with an optional filter
  28078. *
  28079. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28080. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28081. */
  28082. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28083. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28084. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28085. filterPredicate = filterPredicate || (function () { return true; });
  28086. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28087. mesh.computeWorldMatrix(true);
  28088. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28089. return;
  28090. }
  28091. var boundingInfo = mesh.getBoundingInfo();
  28092. var minBox = boundingInfo.boundingBox.minimumWorld;
  28093. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28094. BABYLON.Tools.CheckExtends(minBox, min, max);
  28095. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28096. });
  28097. return {
  28098. min: min,
  28099. max: max
  28100. };
  28101. };
  28102. /**
  28103. * Creates or updates the octree used to boost selection (picking)
  28104. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  28105. * @param maxCapacity defines the maximum capacity per leaf
  28106. * @param maxDepth defines the maximum depth of the octree
  28107. * @returns an octree of AbstractMesh
  28108. */
  28109. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  28110. if (maxCapacity === void 0) { maxCapacity = 64; }
  28111. if (maxDepth === void 0) { maxDepth = 2; }
  28112. if (!this._selectionOctree) {
  28113. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  28114. }
  28115. var worldExtends = this.getWorldExtends();
  28116. // Update octree
  28117. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  28118. return this._selectionOctree;
  28119. };
  28120. // Picking
  28121. /**
  28122. * Creates a ray that can be used to pick in the scene
  28123. * @param x defines the x coordinate of the origin (on-screen)
  28124. * @param y defines the y coordinate of the origin (on-screen)
  28125. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28126. * @param camera defines the camera to use for the picking
  28127. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28128. * @returns a Ray
  28129. */
  28130. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28131. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28132. var result = BABYLON.Ray.Zero();
  28133. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28134. return result;
  28135. };
  28136. /**
  28137. * Creates a ray that can be used to pick in the scene
  28138. * @param x defines the x coordinate of the origin (on-screen)
  28139. * @param y defines the y coordinate of the origin (on-screen)
  28140. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28141. * @param result defines the ray where to store the picking ray
  28142. * @param camera defines the camera to use for the picking
  28143. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28144. * @returns the current scene
  28145. */
  28146. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28147. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28148. var engine = this._engine;
  28149. if (!camera) {
  28150. if (!this.activeCamera)
  28151. throw new Error("Active camera not set");
  28152. camera = this.activeCamera;
  28153. }
  28154. var cameraViewport = camera.viewport;
  28155. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28156. // Moving coordinates to local viewport world
  28157. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28158. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28159. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28160. return this;
  28161. };
  28162. /**
  28163. * Creates a ray that can be used to pick in the scene
  28164. * @param x defines the x coordinate of the origin (on-screen)
  28165. * @param y defines the y coordinate of the origin (on-screen)
  28166. * @param camera defines the camera to use for the picking
  28167. * @returns a Ray
  28168. */
  28169. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28170. var result = BABYLON.Ray.Zero();
  28171. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28172. return result;
  28173. };
  28174. /**
  28175. * Creates a ray that can be used to pick in the scene
  28176. * @param x defines the x coordinate of the origin (on-screen)
  28177. * @param y defines the y coordinate of the origin (on-screen)
  28178. * @param result defines the ray where to store the picking ray
  28179. * @param camera defines the camera to use for the picking
  28180. * @returns the current scene
  28181. */
  28182. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28183. if (!BABYLON.PickingInfo) {
  28184. return this;
  28185. }
  28186. var engine = this._engine;
  28187. if (!camera) {
  28188. if (!this.activeCamera)
  28189. throw new Error("Active camera not set");
  28190. camera = this.activeCamera;
  28191. }
  28192. var cameraViewport = camera.viewport;
  28193. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28194. var identity = BABYLON.Matrix.Identity();
  28195. // Moving coordinates to local viewport world
  28196. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28197. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28198. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28199. return this;
  28200. };
  28201. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28202. if (!BABYLON.PickingInfo) {
  28203. return null;
  28204. }
  28205. var pickingInfo = null;
  28206. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28207. var mesh = this.meshes[meshIndex];
  28208. if (predicate) {
  28209. if (!predicate(mesh)) {
  28210. continue;
  28211. }
  28212. }
  28213. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28214. continue;
  28215. }
  28216. var world = mesh.getWorldMatrix();
  28217. var ray = rayFunction(world);
  28218. var result = mesh.intersects(ray, fastCheck);
  28219. if (!result || !result.hit)
  28220. continue;
  28221. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28222. continue;
  28223. pickingInfo = result;
  28224. if (fastCheck) {
  28225. break;
  28226. }
  28227. }
  28228. return pickingInfo || new BABYLON.PickingInfo();
  28229. };
  28230. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28231. if (!BABYLON.PickingInfo) {
  28232. return null;
  28233. }
  28234. var pickingInfos = new Array();
  28235. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28236. var mesh = this.meshes[meshIndex];
  28237. if (predicate) {
  28238. if (!predicate(mesh)) {
  28239. continue;
  28240. }
  28241. }
  28242. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28243. continue;
  28244. }
  28245. var world = mesh.getWorldMatrix();
  28246. var ray = rayFunction(world);
  28247. var result = mesh.intersects(ray, false);
  28248. if (!result || !result.hit)
  28249. continue;
  28250. pickingInfos.push(result);
  28251. }
  28252. return pickingInfos;
  28253. };
  28254. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  28255. if (!BABYLON.PickingInfo) {
  28256. return null;
  28257. }
  28258. var pickingInfo = null;
  28259. if (!camera) {
  28260. if (!this.activeCamera) {
  28261. return null;
  28262. }
  28263. camera = this.activeCamera;
  28264. }
  28265. if (this.spriteManagers.length > 0) {
  28266. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  28267. var spriteManager = this.spriteManagers[spriteIndex];
  28268. if (!spriteManager.isPickable) {
  28269. continue;
  28270. }
  28271. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  28272. if (!result || !result.hit)
  28273. continue;
  28274. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28275. continue;
  28276. pickingInfo = result;
  28277. if (fastCheck) {
  28278. break;
  28279. }
  28280. }
  28281. }
  28282. return pickingInfo || new BABYLON.PickingInfo();
  28283. };
  28284. /** Launch a ray to try to pick a mesh in the scene
  28285. * @param x position on screen
  28286. * @param y position on screen
  28287. * @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
  28288. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28289. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28290. * @returns a PickingInfo
  28291. */
  28292. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28293. var _this = this;
  28294. if (!BABYLON.PickingInfo) {
  28295. return null;
  28296. }
  28297. return this._internalPick(function (world) {
  28298. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28299. return _this._tempPickingRay;
  28300. }, predicate, fastCheck);
  28301. };
  28302. /** Launch a ray to try to pick a sprite in the scene
  28303. * @param x position on screen
  28304. * @param y position on screen
  28305. * @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
  28306. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28307. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28308. * @returns a PickingInfo
  28309. */
  28310. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  28311. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  28312. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  28313. };
  28314. /** Use the given ray to pick a mesh in the scene
  28315. * @param ray The ray to use to pick meshes
  28316. * @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
  28317. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28318. * @returns a PickingInfo
  28319. */
  28320. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28321. var _this = this;
  28322. return this._internalPick(function (world) {
  28323. if (!_this._pickWithRayInverseMatrix) {
  28324. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28325. }
  28326. world.invertToRef(_this._pickWithRayInverseMatrix);
  28327. if (!_this._cachedRayForTransform) {
  28328. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28329. }
  28330. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28331. return _this._cachedRayForTransform;
  28332. }, predicate, fastCheck);
  28333. };
  28334. /**
  28335. * Launch a ray to try to pick a mesh in the scene
  28336. * @param x X position on screen
  28337. * @param y Y position on screen
  28338. * @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
  28339. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28340. * @returns an array of PickingInfo
  28341. */
  28342. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28343. var _this = this;
  28344. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28345. };
  28346. /**
  28347. * Launch a ray to try to pick a mesh in the scene
  28348. * @param ray Ray to use
  28349. * @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
  28350. * @returns an array of PickingInfo
  28351. */
  28352. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28353. var _this = this;
  28354. return this._internalMultiPick(function (world) {
  28355. if (!_this._pickWithRayInverseMatrix) {
  28356. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28357. }
  28358. world.invertToRef(_this._pickWithRayInverseMatrix);
  28359. if (!_this._cachedRayForTransform) {
  28360. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28361. }
  28362. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28363. return _this._cachedRayForTransform;
  28364. }, predicate);
  28365. };
  28366. /**
  28367. * Force the value of meshUnderPointer
  28368. * @param mesh defines the mesh to use
  28369. */
  28370. Scene.prototype.setPointerOverMesh = function (mesh) {
  28371. if (this._pointerOverMesh === mesh) {
  28372. return;
  28373. }
  28374. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28375. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28376. }
  28377. this._pointerOverMesh = mesh;
  28378. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28379. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28380. }
  28381. };
  28382. /**
  28383. * Gets the mesh under the pointer
  28384. * @returns a Mesh or null if no mesh is under the pointer
  28385. */
  28386. Scene.prototype.getPointerOverMesh = function () {
  28387. return this._pointerOverMesh;
  28388. };
  28389. /**
  28390. * Force the sprite under the pointer
  28391. * @param sprite defines the sprite to use
  28392. */
  28393. Scene.prototype.setPointerOverSprite = function (sprite) {
  28394. if (this._pointerOverSprite === sprite) {
  28395. return;
  28396. }
  28397. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28398. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28399. }
  28400. this._pointerOverSprite = sprite;
  28401. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28402. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28403. }
  28404. };
  28405. /**
  28406. * Gets the sprite under the pointer
  28407. * @returns a Sprite or null if no sprite is under the pointer
  28408. */
  28409. Scene.prototype.getPointerOverSprite = function () {
  28410. return this._pointerOverSprite;
  28411. };
  28412. // Physics
  28413. /**
  28414. * Gets the current physics engine
  28415. * @returns a PhysicsEngine or null if none attached
  28416. */
  28417. Scene.prototype.getPhysicsEngine = function () {
  28418. return this._physicsEngine;
  28419. };
  28420. /**
  28421. * Enables physics to the current scene
  28422. * @param gravity defines the scene's gravity for the physics engine
  28423. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  28424. * @return a boolean indicating if the physics engine was initialized
  28425. */
  28426. Scene.prototype.enablePhysics = function (gravity, plugin) {
  28427. if (gravity === void 0) { gravity = null; }
  28428. if (this._physicsEngine) {
  28429. return true;
  28430. }
  28431. try {
  28432. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  28433. return true;
  28434. }
  28435. catch (e) {
  28436. BABYLON.Tools.Error(e.message);
  28437. return false;
  28438. }
  28439. };
  28440. /**
  28441. * Disables and disposes the physics engine associated with the scene
  28442. */
  28443. Scene.prototype.disablePhysicsEngine = function () {
  28444. if (!this._physicsEngine) {
  28445. return;
  28446. }
  28447. this._physicsEngine.dispose();
  28448. this._physicsEngine = null;
  28449. };
  28450. /**
  28451. * Gets a boolean indicating if there is an active physics engine
  28452. * @returns a boolean indicating if there is an active physics engine
  28453. */
  28454. Scene.prototype.isPhysicsEnabled = function () {
  28455. return this._physicsEngine !== undefined;
  28456. };
  28457. /**
  28458. * Deletes a physics compound impostor
  28459. * @param compound defines the compound to delete
  28460. */
  28461. Scene.prototype.deleteCompoundImpostor = function (compound) {
  28462. var mesh = compound.parts[0].mesh;
  28463. if (mesh.physicsImpostor) {
  28464. mesh.physicsImpostor.dispose( /*true*/);
  28465. mesh.physicsImpostor = null;
  28466. }
  28467. };
  28468. // Misc.
  28469. /** @hidden */
  28470. Scene.prototype._rebuildGeometries = function () {
  28471. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  28472. var geometry = _a[_i];
  28473. geometry._rebuild();
  28474. }
  28475. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28476. var mesh = _c[_b];
  28477. mesh._rebuild();
  28478. }
  28479. if (this.postProcessManager) {
  28480. this.postProcessManager._rebuild();
  28481. }
  28482. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  28483. var layer = _e[_d];
  28484. layer._rebuild();
  28485. }
  28486. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  28487. var effectLayer = _g[_f];
  28488. effectLayer._rebuild();
  28489. }
  28490. if (this._boundingBoxRenderer) {
  28491. this._boundingBoxRenderer._rebuild();
  28492. }
  28493. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  28494. var system = _j[_h];
  28495. system.rebuild();
  28496. }
  28497. if (this._postProcessRenderPipelineManager) {
  28498. this._postProcessRenderPipelineManager._rebuild();
  28499. }
  28500. };
  28501. /** @hidden */
  28502. Scene.prototype._rebuildTextures = function () {
  28503. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28504. var texture = _a[_i];
  28505. texture._rebuild();
  28506. }
  28507. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28508. };
  28509. /**
  28510. * Creates a default light for the scene.
  28511. * @param replace Whether to replace the existing lights in the scene.
  28512. */
  28513. Scene.prototype.createDefaultLight = function (replace) {
  28514. if (replace === void 0) { replace = false; }
  28515. // Dispose existing light in replace mode.
  28516. if (replace) {
  28517. if (this.lights) {
  28518. for (var i = 0; i < this.lights.length; i++) {
  28519. this.lights[i].dispose();
  28520. }
  28521. }
  28522. }
  28523. // Light
  28524. if (this.lights.length === 0) {
  28525. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  28526. }
  28527. };
  28528. /**
  28529. * Creates a default camera for the scene.
  28530. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  28531. * @param replace Whether to replace the existing active camera in the scene.
  28532. * @param attachCameraControls Whether to attach camera controls to the canvas.
  28533. */
  28534. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  28535. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28536. if (replace === void 0) { replace = false; }
  28537. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28538. // Dispose existing camera in replace mode.
  28539. if (replace) {
  28540. if (this.activeCamera) {
  28541. this.activeCamera.dispose();
  28542. this.activeCamera = null;
  28543. }
  28544. }
  28545. // Camera
  28546. if (!this.activeCamera) {
  28547. var worldExtends = this.getWorldExtends();
  28548. var worldSize = worldExtends.max.subtract(worldExtends.min);
  28549. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  28550. var camera;
  28551. var radius = worldSize.length() * 1.5;
  28552. // empty scene scenario!
  28553. if (!isFinite(radius)) {
  28554. radius = 1;
  28555. worldCenter.copyFromFloats(0, 0, 0);
  28556. }
  28557. if (createArcRotateCamera) {
  28558. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  28559. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  28560. arcRotateCamera.wheelPrecision = 100 / radius;
  28561. camera = arcRotateCamera;
  28562. }
  28563. else {
  28564. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  28565. freeCamera.setTarget(worldCenter);
  28566. camera = freeCamera;
  28567. }
  28568. camera.minZ = radius * 0.01;
  28569. camera.maxZ = radius * 1000;
  28570. camera.speed = radius * 0.2;
  28571. this.activeCamera = camera;
  28572. var canvas = this.getEngine().getRenderingCanvas();
  28573. if (attachCameraControls && canvas) {
  28574. camera.attachControl(canvas);
  28575. }
  28576. }
  28577. };
  28578. /**
  28579. * Creates a default camera and a default light
  28580. * @param createArcRotateCamera defines that the camera will be an ArcRotateCamera
  28581. * @param replace defines if the camera and/or light will replace the existing ones
  28582. * @param attachCameraControls defines if attachControl will be called on the new camera
  28583. */
  28584. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  28585. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28586. if (replace === void 0) { replace = false; }
  28587. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28588. this.createDefaultLight(replace);
  28589. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  28590. };
  28591. /**
  28592. * Creates a new sky box
  28593. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28594. * @param environmentTexture defines the texture to use as environment texture
  28595. * @param pbr defines if PBRMaterial must be used instead of StandardMaterial
  28596. * @param scale defines the overall scale of the skybox
  28597. * @param blur defines if blurring must be applied to the environment texture (works only with pbr === true)
  28598. * @param setGlobalEnvTexture defines a boolean indicating that scene.environmentTexture must match the current skybox texture (true by default)
  28599. * @returns a new mesh holding the sky box
  28600. */
  28601. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  28602. if (pbr === void 0) { pbr = false; }
  28603. if (scale === void 0) { scale = 1000; }
  28604. if (blur === void 0) { blur = 0; }
  28605. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  28606. if (!environmentTexture) {
  28607. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  28608. return null;
  28609. }
  28610. if (setGlobalEnvTexture) {
  28611. if (environmentTexture) {
  28612. this.environmentTexture = environmentTexture;
  28613. }
  28614. }
  28615. // Skybox
  28616. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  28617. if (pbr) {
  28618. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  28619. hdrSkyboxMaterial.backFaceCulling = false;
  28620. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  28621. if (hdrSkyboxMaterial.reflectionTexture) {
  28622. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28623. }
  28624. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  28625. hdrSkyboxMaterial.disableLighting = true;
  28626. hdrSkyboxMaterial.twoSidedLighting = true;
  28627. hdrSkybox.infiniteDistance = true;
  28628. hdrSkybox.material = hdrSkyboxMaterial;
  28629. }
  28630. else {
  28631. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  28632. skyboxMaterial.backFaceCulling = false;
  28633. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  28634. if (skyboxMaterial.reflectionTexture) {
  28635. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28636. }
  28637. skyboxMaterial.disableLighting = true;
  28638. hdrSkybox.infiniteDistance = true;
  28639. hdrSkybox.material = skyboxMaterial;
  28640. }
  28641. return hdrSkybox;
  28642. };
  28643. /**
  28644. * Creates a new environment
  28645. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28646. * @param options defines the options you can use to configure the environment
  28647. * @returns the new EnvironmentHelper
  28648. */
  28649. Scene.prototype.createDefaultEnvironment = function (options) {
  28650. if (BABYLON.EnvironmentHelper) {
  28651. return new BABYLON.EnvironmentHelper(options, this);
  28652. }
  28653. return null;
  28654. };
  28655. /**
  28656. * Creates a new VREXperienceHelper
  28657. * @see http://doc.babylonjs.com/how_to/webvr_helper
  28658. * @param webVROptions defines the options used to create the new VREXperienceHelper
  28659. * @returns a new VREXperienceHelper
  28660. */
  28661. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  28662. if (webVROptions === void 0) { webVROptions = {}; }
  28663. return new BABYLON.VRExperienceHelper(this, webVROptions);
  28664. };
  28665. // Tags
  28666. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  28667. if (tagsQuery === undefined) {
  28668. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  28669. return list;
  28670. }
  28671. var listByTags = [];
  28672. forEach = forEach || (function (item) { return; });
  28673. for (var i in list) {
  28674. var item = list[i];
  28675. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  28676. listByTags.push(item);
  28677. forEach(item);
  28678. }
  28679. }
  28680. return listByTags;
  28681. };
  28682. /**
  28683. * Get a list of meshes by tags
  28684. * @param tagsQuery defines the tags query to use
  28685. * @param forEach defines a predicate used to filter results
  28686. * @returns an array of Mesh
  28687. */
  28688. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  28689. return this._getByTags(this.meshes, tagsQuery, forEach);
  28690. };
  28691. /**
  28692. * Get a list of cameras by tags
  28693. * @param tagsQuery defines the tags query to use
  28694. * @param forEach defines a predicate used to filter results
  28695. * @returns an array of Camera
  28696. */
  28697. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  28698. return this._getByTags(this.cameras, tagsQuery, forEach);
  28699. };
  28700. /**
  28701. * Get a list of lights by tags
  28702. * @param tagsQuery defines the tags query to use
  28703. * @param forEach defines a predicate used to filter results
  28704. * @returns an array of Light
  28705. */
  28706. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  28707. return this._getByTags(this.lights, tagsQuery, forEach);
  28708. };
  28709. /**
  28710. * Get a list of materials by tags
  28711. * @param tagsQuery defines the tags query to use
  28712. * @param forEach defines a predicate used to filter results
  28713. * @returns an array of Material
  28714. */
  28715. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  28716. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  28717. };
  28718. /**
  28719. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  28720. * This allowed control for front to back rendering or reversly depending of the special needs.
  28721. *
  28722. * @param renderingGroupId The rendering group id corresponding to its index
  28723. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  28724. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  28725. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  28726. */
  28727. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  28728. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  28729. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  28730. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  28731. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  28732. };
  28733. /**
  28734. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  28735. *
  28736. * @param renderingGroupId The rendering group id corresponding to its index
  28737. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  28738. * @param depth Automatically clears depth between groups if true and autoClear is true.
  28739. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  28740. */
  28741. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  28742. if (depth === void 0) { depth = true; }
  28743. if (stencil === void 0) { stencil = true; }
  28744. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  28745. };
  28746. /**
  28747. * Will flag all materials as dirty to trigger new shader compilation
  28748. * @param flag defines the flag used to specify which material part must be marked as dirty
  28749. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  28750. */
  28751. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  28752. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  28753. var material = _a[_i];
  28754. if (predicate && !predicate(material)) {
  28755. continue;
  28756. }
  28757. material.markAsDirty(flag);
  28758. }
  28759. };
  28760. /** @hidden */
  28761. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  28762. var _this = this;
  28763. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  28764. this._activeRequests.push(request);
  28765. request.onCompleteObservable.add(function (request) {
  28766. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  28767. });
  28768. return request;
  28769. };
  28770. /** @hidden */
  28771. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  28772. var _this = this;
  28773. return new Promise(function (resolve, reject) {
  28774. _this._loadFile(url, function (data) {
  28775. resolve(data);
  28776. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  28777. reject(exception);
  28778. });
  28779. });
  28780. };
  28781. // Statics
  28782. Scene._FOGMODE_NONE = 0;
  28783. Scene._FOGMODE_EXP = 1;
  28784. Scene._FOGMODE_EXP2 = 2;
  28785. Scene._FOGMODE_LINEAR = 3;
  28786. Scene._uniqueIdCounter = 0;
  28787. /**
  28788. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  28789. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28790. */
  28791. Scene.MinDeltaTime = 1.0;
  28792. /**
  28793. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  28794. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28795. */
  28796. Scene.MaxDeltaTime = 1000.0;
  28797. /** The distance in pixel that you have to move to prevent some events */
  28798. Scene.DragMovementThreshold = 10; // in pixels
  28799. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  28800. Scene.LongPressDelay = 500; // in milliseconds
  28801. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  28802. Scene.DoubleClickDelay = 300; // in milliseconds
  28803. /** If you need to check double click without raising a single click at first click, enable this flag */
  28804. Scene.ExclusiveDoubleClickMode = false;
  28805. return Scene;
  28806. }());
  28807. BABYLON.Scene = Scene;
  28808. })(BABYLON || (BABYLON = {}));
  28809. //# sourceMappingURL=babylon.scene.js.map
  28810. var BABYLON;
  28811. (function (BABYLON) {
  28812. /**
  28813. * Set of assets to keep when moving a scene into an asset container.
  28814. */
  28815. var KeepAssets = /** @class */ (function () {
  28816. function KeepAssets() {
  28817. /**
  28818. * Cameras to keep.
  28819. */
  28820. this.cameras = new Array();
  28821. /**
  28822. * Lights to keep.
  28823. */
  28824. this.lights = new Array();
  28825. /**
  28826. * Meshes to keep.
  28827. */
  28828. this.meshes = new Array();
  28829. /**
  28830. * Skeletons to keep.
  28831. */
  28832. this.skeletons = new Array();
  28833. /**
  28834. * ParticleSystems to keep.
  28835. */
  28836. this.particleSystems = new Array();
  28837. /**
  28838. * Animations to keep.
  28839. */
  28840. this.animations = new Array();
  28841. /**
  28842. * AnimationGroups to keep.
  28843. */
  28844. this.animationGroups = new Array();
  28845. /**
  28846. * MultiMaterials to keep.
  28847. */
  28848. this.multiMaterials = new Array();
  28849. /**
  28850. * Materials to keep.
  28851. */
  28852. this.materials = new Array();
  28853. /**
  28854. * MorphTargetManagers to keep.
  28855. */
  28856. this.morphTargetManagers = new Array();
  28857. /**
  28858. * Geometries to keep.
  28859. */
  28860. this.geometries = new Array();
  28861. /**
  28862. * TransformNodes to keep.
  28863. */
  28864. this.transformNodes = new Array();
  28865. /**
  28866. * LensFlareSystems to keep.
  28867. */
  28868. this.lensFlareSystems = new Array();
  28869. /**
  28870. * ShadowGenerators to keep.
  28871. */
  28872. this.shadowGenerators = new Array();
  28873. /**
  28874. * ActionManagers to keep.
  28875. */
  28876. this.actionManagers = new Array();
  28877. /**
  28878. * Sounds to keep.
  28879. */
  28880. this.sounds = new Array();
  28881. /**
  28882. * Textures to keep.
  28883. */
  28884. this.textures = new Array();
  28885. /**
  28886. * Effect layers to keep.
  28887. */
  28888. this.effectLayers = new Array();
  28889. }
  28890. return KeepAssets;
  28891. }());
  28892. BABYLON.KeepAssets = KeepAssets;
  28893. /**
  28894. * Container with a set of assets that can be added or removed from a scene.
  28895. */
  28896. var AssetContainer = /** @class */ (function () {
  28897. /**
  28898. * Instantiates an AssetContainer.
  28899. * @param scene The scene the AssetContainer belongs to.
  28900. */
  28901. function AssetContainer(scene) {
  28902. // Objects
  28903. /**
  28904. * Cameras populated in the container.
  28905. */
  28906. this.cameras = new Array();
  28907. /**
  28908. * Lights populated in the container.
  28909. */
  28910. this.lights = new Array();
  28911. /**
  28912. * Meshes populated in the container.
  28913. */
  28914. this.meshes = new Array();
  28915. /**
  28916. * Skeletons populated in the container.
  28917. */
  28918. this.skeletons = new Array();
  28919. /**
  28920. * ParticleSystems populated in the container.
  28921. */
  28922. this.particleSystems = new Array();
  28923. /**
  28924. * Animations populated in the container.
  28925. */
  28926. this.animations = new Array();
  28927. /**
  28928. * AnimationGroups populated in the container.
  28929. */
  28930. this.animationGroups = new Array();
  28931. /**
  28932. * MultiMaterials populated in the container.
  28933. */
  28934. this.multiMaterials = new Array();
  28935. /**
  28936. * Materials populated in the container.
  28937. */
  28938. this.materials = new Array();
  28939. /**
  28940. * MorphTargetManagers populated in the container.
  28941. */
  28942. this.morphTargetManagers = new Array();
  28943. /**
  28944. * Geometries populated in the container.
  28945. */
  28946. this.geometries = new Array();
  28947. /**
  28948. * TransformNodes populated in the container.
  28949. */
  28950. this.transformNodes = new Array();
  28951. /**
  28952. * LensFlareSystems populated in the container.
  28953. */
  28954. this.lensFlareSystems = new Array();
  28955. /**
  28956. * ShadowGenerators populated in the container.
  28957. */
  28958. this.shadowGenerators = new Array();
  28959. /**
  28960. * ActionManagers populated in the container.
  28961. */
  28962. this.actionManagers = new Array();
  28963. /**
  28964. * Sounds populated in the container.
  28965. */
  28966. this.sounds = new Array();
  28967. /**
  28968. * Textures populated in the container.
  28969. */
  28970. this.textures = new Array();
  28971. /**
  28972. * Effect layers populated in the container.
  28973. */
  28974. this.effectLayers = new Array();
  28975. this.scene = scene;
  28976. }
  28977. /**
  28978. * Adds all the assets from the container to the scene.
  28979. */
  28980. AssetContainer.prototype.addAllToScene = function () {
  28981. var _this = this;
  28982. this.cameras.forEach(function (o) {
  28983. _this.scene.addCamera(o);
  28984. });
  28985. this.lights.forEach(function (o) {
  28986. _this.scene.addLight(o);
  28987. });
  28988. this.meshes.forEach(function (o) {
  28989. _this.scene.addMesh(o);
  28990. });
  28991. this.skeletons.forEach(function (o) {
  28992. _this.scene.addSkeleton(o);
  28993. });
  28994. this.particleSystems.forEach(function (o) {
  28995. _this.scene.addParticleSystem(o);
  28996. });
  28997. this.animations.forEach(function (o) {
  28998. _this.scene.addAnimation(o);
  28999. });
  29000. this.animationGroups.forEach(function (o) {
  29001. _this.scene.addAnimationGroup(o);
  29002. });
  29003. this.multiMaterials.forEach(function (o) {
  29004. _this.scene.addMultiMaterial(o);
  29005. });
  29006. this.materials.forEach(function (o) {
  29007. _this.scene.addMaterial(o);
  29008. });
  29009. this.morphTargetManagers.forEach(function (o) {
  29010. _this.scene.addMorphTargetManager(o);
  29011. });
  29012. this.geometries.forEach(function (o) {
  29013. _this.scene.addGeometry(o);
  29014. });
  29015. this.transformNodes.forEach(function (o) {
  29016. _this.scene.addTransformNode(o);
  29017. });
  29018. this.lensFlareSystems.forEach(function (o) {
  29019. _this.scene.addLensFlareSystem(o);
  29020. });
  29021. this.actionManagers.forEach(function (o) {
  29022. _this.scene.addActionManager(o);
  29023. });
  29024. this.sounds.forEach(function (o) {
  29025. o.play();
  29026. o.autoplay = true;
  29027. _this.scene.mainSoundTrack.AddSound(o);
  29028. });
  29029. this.textures.forEach(function (o) {
  29030. _this.scene.addTexture(o);
  29031. });
  29032. this.effectLayers.forEach(function (o) {
  29033. _this.scene.addEffectLayer(o);
  29034. });
  29035. };
  29036. /**
  29037. * Removes all the assets in the container from the scene
  29038. */
  29039. AssetContainer.prototype.removeAllFromScene = function () {
  29040. var _this = this;
  29041. this.cameras.forEach(function (o) {
  29042. _this.scene.removeCamera(o);
  29043. });
  29044. this.lights.forEach(function (o) {
  29045. _this.scene.removeLight(o);
  29046. });
  29047. this.meshes.forEach(function (o) {
  29048. _this.scene.removeMesh(o);
  29049. });
  29050. this.skeletons.forEach(function (o) {
  29051. _this.scene.removeSkeleton(o);
  29052. });
  29053. this.particleSystems.forEach(function (o) {
  29054. _this.scene.removeParticleSystem(o);
  29055. });
  29056. this.animations.forEach(function (o) {
  29057. _this.scene.removeAnimation(o);
  29058. });
  29059. this.animationGroups.forEach(function (o) {
  29060. _this.scene.removeAnimationGroup(o);
  29061. });
  29062. this.multiMaterials.forEach(function (o) {
  29063. _this.scene.removeMultiMaterial(o);
  29064. });
  29065. this.materials.forEach(function (o) {
  29066. _this.scene.removeMaterial(o);
  29067. });
  29068. this.morphTargetManagers.forEach(function (o) {
  29069. _this.scene.removeMorphTargetManager(o);
  29070. });
  29071. this.geometries.forEach(function (o) {
  29072. _this.scene.removeGeometry(o);
  29073. });
  29074. this.transformNodes.forEach(function (o) {
  29075. _this.scene.removeTransformNode(o);
  29076. });
  29077. this.lensFlareSystems.forEach(function (o) {
  29078. _this.scene.removeLensFlareSystem(o);
  29079. });
  29080. this.actionManagers.forEach(function (o) {
  29081. _this.scene.removeActionManager(o);
  29082. });
  29083. this.sounds.forEach(function (o) {
  29084. o.stop();
  29085. o.autoplay = false;
  29086. _this.scene.mainSoundTrack.RemoveSound(o);
  29087. });
  29088. this.textures.forEach(function (o) {
  29089. _this.scene.removeTexture(o);
  29090. });
  29091. this.effectLayers.forEach(function (o) {
  29092. _this.scene.removeEffectLayer(o);
  29093. });
  29094. };
  29095. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  29096. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  29097. var asset = sourceAssets_1[_i];
  29098. var move = true;
  29099. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  29100. var keepAsset = keepAssets_1[_a];
  29101. if (asset === keepAsset) {
  29102. move = false;
  29103. break;
  29104. }
  29105. }
  29106. if (move) {
  29107. targetAssets.push(asset);
  29108. }
  29109. }
  29110. };
  29111. /**
  29112. * Removes all the assets contained in the scene and adds them to the container.
  29113. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  29114. */
  29115. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29116. if (keepAssets === undefined) {
  29117. keepAssets = new KeepAssets();
  29118. }
  29119. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  29120. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  29121. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  29122. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  29123. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  29124. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  29125. this._moveAssets(this.scene.animationGroups, this.animationGroups, keepAssets.animationGroups);
  29126. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  29127. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  29128. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  29129. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  29130. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  29131. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  29132. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  29133. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  29134. this._moveAssets(this.scene.textures, this.textures, keepAssets.textures);
  29135. this._moveAssets(this.scene.effectLayers, this.effectLayers, keepAssets.effectLayers);
  29136. this.removeAllFromScene();
  29137. };
  29138. return AssetContainer;
  29139. }());
  29140. BABYLON.AssetContainer = AssetContainer;
  29141. })(BABYLON || (BABYLON = {}));
  29142. //# sourceMappingURL=babylon.assetContainer.js.map
  29143. var BABYLON;
  29144. (function (BABYLON) {
  29145. var Buffer = /** @class */ (function () {
  29146. /**
  29147. * Constructor
  29148. * @param engine the engine
  29149. * @param data the data to use for this buffer
  29150. * @param updatable whether the data is updatable
  29151. * @param stride the stride (optional)
  29152. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29153. * @param instanced whether the buffer is instanced (optional)
  29154. * @param useBytes set to true if the stride in in bytes (optional)
  29155. */
  29156. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29157. if (stride === void 0) { stride = 0; }
  29158. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29159. if (instanced === void 0) { instanced = false; }
  29160. if (useBytes === void 0) { useBytes = false; }
  29161. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29162. this._engine = engine.getScene().getEngine();
  29163. }
  29164. else {
  29165. this._engine = engine;
  29166. }
  29167. this._updatable = updatable;
  29168. this._instanced = instanced;
  29169. this._data = data;
  29170. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29171. if (!postponeInternalCreation) { // by default
  29172. this.create();
  29173. }
  29174. }
  29175. /**
  29176. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  29177. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29178. * @param offset defines offset in the buffer (0 by default)
  29179. * @param size defines the size in floats of attributes (position is 3 for instance)
  29180. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29181. * @param instanced defines if the vertex buffer contains indexed data
  29182. * @param useBytes defines if the offset and stride are in bytes
  29183. * @returns the new vertex buffer
  29184. */
  29185. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29186. if (useBytes === void 0) { useBytes = false; }
  29187. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29188. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29189. // a lot of these parameters are ignored as they are overriden by the buffer
  29190. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29191. };
  29192. // Properties
  29193. Buffer.prototype.isUpdatable = function () {
  29194. return this._updatable;
  29195. };
  29196. Buffer.prototype.getData = function () {
  29197. return this._data;
  29198. };
  29199. Buffer.prototype.getBuffer = function () {
  29200. return this._buffer;
  29201. };
  29202. /**
  29203. * Gets the stride in float32 units (i.e. byte stride / 4).
  29204. * May not be an integer if the byte stride is not divisible by 4.
  29205. * DEPRECATED. Use byteStride instead.
  29206. * @returns the stride in float32 units
  29207. */
  29208. Buffer.prototype.getStrideSize = function () {
  29209. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29210. };
  29211. // Methods
  29212. Buffer.prototype.create = function (data) {
  29213. if (data === void 0) { data = null; }
  29214. if (!data && this._buffer) {
  29215. return; // nothing to do
  29216. }
  29217. data = data || this._data;
  29218. if (!data) {
  29219. return;
  29220. }
  29221. if (!this._buffer) { // create buffer
  29222. if (this._updatable) {
  29223. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29224. this._data = data;
  29225. }
  29226. else {
  29227. this._buffer = this._engine.createVertexBuffer(data);
  29228. }
  29229. }
  29230. else if (this._updatable) { // update buffer
  29231. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29232. this._data = data;
  29233. }
  29234. };
  29235. Buffer.prototype._rebuild = function () {
  29236. this._buffer = null;
  29237. this.create(this._data);
  29238. };
  29239. Buffer.prototype.update = function (data) {
  29240. this.create(data);
  29241. };
  29242. /**
  29243. * Updates the data directly.
  29244. * @param data the new data
  29245. * @param offset the new offset
  29246. * @param vertexCount the vertex count (optional)
  29247. * @param useBytes set to true if the offset is in bytes
  29248. */
  29249. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29250. if (useBytes === void 0) { useBytes = false; }
  29251. if (!this._buffer) {
  29252. return;
  29253. }
  29254. if (this._updatable) { // update buffer
  29255. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29256. this._data = null;
  29257. }
  29258. };
  29259. Buffer.prototype.dispose = function () {
  29260. if (!this._buffer) {
  29261. return;
  29262. }
  29263. if (this._engine._releaseBuffer(this._buffer)) {
  29264. this._buffer = null;
  29265. }
  29266. };
  29267. return Buffer;
  29268. }());
  29269. BABYLON.Buffer = Buffer;
  29270. })(BABYLON || (BABYLON = {}));
  29271. //# sourceMappingURL=babylon.buffer.js.map
  29272. var BABYLON;
  29273. (function (BABYLON) {
  29274. var VertexBuffer = /** @class */ (function () {
  29275. /**
  29276. * Constructor
  29277. * @param engine the engine
  29278. * @param data the data to use for this vertex buffer
  29279. * @param kind the vertex buffer kind
  29280. * @param updatable whether the data is updatable
  29281. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29282. * @param stride the stride (optional)
  29283. * @param instanced whether the buffer is instanced (optional)
  29284. * @param offset the offset of the data (optional)
  29285. * @param size the number of components (optional)
  29286. * @param type the type of the component (optional)
  29287. * @param normalized whether the data contains normalized data (optional)
  29288. * @param useBytes set to true if stride and offset are in bytes (optional)
  29289. */
  29290. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29291. if (normalized === void 0) { normalized = false; }
  29292. if (useBytes === void 0) { useBytes = false; }
  29293. if (data instanceof BABYLON.Buffer) {
  29294. this._buffer = data;
  29295. this._ownsBuffer = false;
  29296. }
  29297. else {
  29298. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29299. this._ownsBuffer = true;
  29300. }
  29301. this._kind = kind;
  29302. if (type == undefined) {
  29303. var data_1 = this.getData();
  29304. this.type = VertexBuffer.FLOAT;
  29305. if (data_1 instanceof Int8Array)
  29306. this.type = VertexBuffer.BYTE;
  29307. else if (data_1 instanceof Uint8Array)
  29308. this.type = VertexBuffer.UNSIGNED_BYTE;
  29309. else if (data_1 instanceof Int16Array)
  29310. this.type = VertexBuffer.SHORT;
  29311. else if (data_1 instanceof Uint16Array)
  29312. this.type = VertexBuffer.UNSIGNED_SHORT;
  29313. else if (data_1 instanceof Int32Array)
  29314. this.type = VertexBuffer.INT;
  29315. else if (data_1 instanceof Uint32Array)
  29316. this.type = VertexBuffer.UNSIGNED_INT;
  29317. }
  29318. else {
  29319. this.type = type;
  29320. }
  29321. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29322. if (useBytes) {
  29323. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29324. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29325. this.byteOffset = offset || 0;
  29326. }
  29327. else {
  29328. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29329. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29330. this.byteOffset = (offset || 0) * typeByteLength;
  29331. }
  29332. this.normalized = normalized;
  29333. this._instanced = instanced !== undefined ? instanced : false;
  29334. this._instanceDivisor = instanced ? 1 : 0;
  29335. }
  29336. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29337. /**
  29338. * Gets or sets the instance divisor when in instanced mode
  29339. */
  29340. get: function () {
  29341. return this._instanceDivisor;
  29342. },
  29343. set: function (value) {
  29344. this._instanceDivisor = value;
  29345. if (value == 0) {
  29346. this._instanced = false;
  29347. }
  29348. else {
  29349. this._instanced = true;
  29350. }
  29351. },
  29352. enumerable: true,
  29353. configurable: true
  29354. });
  29355. VertexBuffer.prototype._rebuild = function () {
  29356. if (!this._buffer) {
  29357. return;
  29358. }
  29359. this._buffer._rebuild();
  29360. };
  29361. /**
  29362. * Returns the kind of the VertexBuffer (string).
  29363. */
  29364. VertexBuffer.prototype.getKind = function () {
  29365. return this._kind;
  29366. };
  29367. // Properties
  29368. /**
  29369. * Boolean : is the VertexBuffer updatable ?
  29370. */
  29371. VertexBuffer.prototype.isUpdatable = function () {
  29372. return this._buffer.isUpdatable();
  29373. };
  29374. /**
  29375. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29376. */
  29377. VertexBuffer.prototype.getData = function () {
  29378. return this._buffer.getData();
  29379. };
  29380. /**
  29381. * Returns the WebGLBuffer associated to the VertexBuffer.
  29382. */
  29383. VertexBuffer.prototype.getBuffer = function () {
  29384. return this._buffer.getBuffer();
  29385. };
  29386. /**
  29387. * Returns the stride as a multiple of the type byte length.
  29388. * DEPRECATED. Use byteStride instead.
  29389. */
  29390. VertexBuffer.prototype.getStrideSize = function () {
  29391. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29392. };
  29393. /**
  29394. * Returns the offset as a multiple of the type byte length.
  29395. * DEPRECATED. Use byteOffset instead.
  29396. */
  29397. VertexBuffer.prototype.getOffset = function () {
  29398. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29399. };
  29400. /**
  29401. * Returns the number of components per vertex attribute (integer).
  29402. */
  29403. VertexBuffer.prototype.getSize = function () {
  29404. return this._size;
  29405. };
  29406. /**
  29407. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29408. */
  29409. VertexBuffer.prototype.getIsInstanced = function () {
  29410. return this._instanced;
  29411. };
  29412. /**
  29413. * Returns the instancing divisor, zero for non-instanced (integer).
  29414. */
  29415. VertexBuffer.prototype.getInstanceDivisor = function () {
  29416. return this._instanceDivisor;
  29417. };
  29418. // Methods
  29419. /**
  29420. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29421. * Returns the created WebGLBuffer.
  29422. */
  29423. VertexBuffer.prototype.create = function (data) {
  29424. return this._buffer.create(data);
  29425. };
  29426. /**
  29427. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29428. * This function will create a new buffer if the current one is not updatable
  29429. * Returns the updated WebGLBuffer.
  29430. */
  29431. VertexBuffer.prototype.update = function (data) {
  29432. return this._buffer.update(data);
  29433. };
  29434. /**
  29435. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29436. * Returns the directly updated WebGLBuffer.
  29437. * @param data the new data
  29438. * @param offset the new offset
  29439. * @param useBytes set to true if the offset is in bytes
  29440. */
  29441. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29442. if (useBytes === void 0) { useBytes = false; }
  29443. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29444. };
  29445. /**
  29446. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29447. */
  29448. VertexBuffer.prototype.dispose = function () {
  29449. if (this._ownsBuffer) {
  29450. this._buffer.dispose();
  29451. }
  29452. };
  29453. /**
  29454. * Enumerates each value of this vertex buffer as numbers.
  29455. * @param count the number of values to enumerate
  29456. * @param callback the callback function called for each value
  29457. */
  29458. VertexBuffer.prototype.forEach = function (count, callback) {
  29459. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29460. };
  29461. Object.defineProperty(VertexBuffer, "PositionKind", {
  29462. get: function () {
  29463. return VertexBuffer._PositionKind;
  29464. },
  29465. enumerable: true,
  29466. configurable: true
  29467. });
  29468. Object.defineProperty(VertexBuffer, "NormalKind", {
  29469. get: function () {
  29470. return VertexBuffer._NormalKind;
  29471. },
  29472. enumerable: true,
  29473. configurable: true
  29474. });
  29475. Object.defineProperty(VertexBuffer, "TangentKind", {
  29476. get: function () {
  29477. return VertexBuffer._TangentKind;
  29478. },
  29479. enumerable: true,
  29480. configurable: true
  29481. });
  29482. Object.defineProperty(VertexBuffer, "UVKind", {
  29483. get: function () {
  29484. return VertexBuffer._UVKind;
  29485. },
  29486. enumerable: true,
  29487. configurable: true
  29488. });
  29489. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29490. get: function () {
  29491. return VertexBuffer._UV2Kind;
  29492. },
  29493. enumerable: true,
  29494. configurable: true
  29495. });
  29496. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29497. get: function () {
  29498. return VertexBuffer._UV3Kind;
  29499. },
  29500. enumerable: true,
  29501. configurable: true
  29502. });
  29503. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29504. get: function () {
  29505. return VertexBuffer._UV4Kind;
  29506. },
  29507. enumerable: true,
  29508. configurable: true
  29509. });
  29510. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29511. get: function () {
  29512. return VertexBuffer._UV5Kind;
  29513. },
  29514. enumerable: true,
  29515. configurable: true
  29516. });
  29517. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29518. get: function () {
  29519. return VertexBuffer._UV6Kind;
  29520. },
  29521. enumerable: true,
  29522. configurable: true
  29523. });
  29524. Object.defineProperty(VertexBuffer, "ColorKind", {
  29525. get: function () {
  29526. return VertexBuffer._ColorKind;
  29527. },
  29528. enumerable: true,
  29529. configurable: true
  29530. });
  29531. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29532. get: function () {
  29533. return VertexBuffer._MatricesIndicesKind;
  29534. },
  29535. enumerable: true,
  29536. configurable: true
  29537. });
  29538. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29539. get: function () {
  29540. return VertexBuffer._MatricesWeightsKind;
  29541. },
  29542. enumerable: true,
  29543. configurable: true
  29544. });
  29545. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29546. get: function () {
  29547. return VertexBuffer._MatricesIndicesExtraKind;
  29548. },
  29549. enumerable: true,
  29550. configurable: true
  29551. });
  29552. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29553. get: function () {
  29554. return VertexBuffer._MatricesWeightsExtraKind;
  29555. },
  29556. enumerable: true,
  29557. configurable: true
  29558. });
  29559. /**
  29560. * Deduces the stride given a kind.
  29561. * @param kind The kind string to deduce
  29562. * @returns The deduced stride
  29563. */
  29564. VertexBuffer.DeduceStride = function (kind) {
  29565. switch (kind) {
  29566. case VertexBuffer.UVKind:
  29567. case VertexBuffer.UV2Kind:
  29568. case VertexBuffer.UV3Kind:
  29569. case VertexBuffer.UV4Kind:
  29570. case VertexBuffer.UV5Kind:
  29571. case VertexBuffer.UV6Kind:
  29572. return 2;
  29573. case VertexBuffer.NormalKind:
  29574. case VertexBuffer.PositionKind:
  29575. return 3;
  29576. case VertexBuffer.ColorKind:
  29577. case VertexBuffer.MatricesIndicesKind:
  29578. case VertexBuffer.MatricesIndicesExtraKind:
  29579. case VertexBuffer.MatricesWeightsKind:
  29580. case VertexBuffer.MatricesWeightsExtraKind:
  29581. case VertexBuffer.TangentKind:
  29582. return 4;
  29583. default:
  29584. throw new Error("Invalid kind '" + kind + "'");
  29585. }
  29586. };
  29587. /**
  29588. * Gets the byte length of the given type.
  29589. * @param type the type
  29590. * @returns the number of bytes
  29591. */
  29592. VertexBuffer.GetTypeByteLength = function (type) {
  29593. switch (type) {
  29594. case VertexBuffer.BYTE:
  29595. case VertexBuffer.UNSIGNED_BYTE:
  29596. return 1;
  29597. case VertexBuffer.SHORT:
  29598. case VertexBuffer.UNSIGNED_SHORT:
  29599. return 2;
  29600. case VertexBuffer.INT:
  29601. case VertexBuffer.FLOAT:
  29602. return 4;
  29603. default:
  29604. throw new Error("Invalid type '" + type + "'");
  29605. }
  29606. };
  29607. /**
  29608. * Enumerates each value of the given parameters as numbers.
  29609. * @param data the data to enumerate
  29610. * @param byteOffset the byte offset of the data
  29611. * @param byteStride the byte stride of the data
  29612. * @param componentCount the number of components per element
  29613. * @param componentType the type of the component
  29614. * @param count the total number of components
  29615. * @param normalized whether the data is normalized
  29616. * @param callback the callback function called for each value
  29617. */
  29618. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29619. if (data instanceof Array) {
  29620. var offset = byteOffset / 4;
  29621. var stride = byteStride / 4;
  29622. for (var index = 0; index < count; index += componentCount) {
  29623. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29624. callback(data[offset + componentIndex], index + componentIndex);
  29625. }
  29626. offset += stride;
  29627. }
  29628. }
  29629. else {
  29630. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29631. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29632. for (var index = 0; index < count; index += componentCount) {
  29633. var componentByteOffset = byteOffset;
  29634. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29635. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29636. callback(value, index + componentIndex);
  29637. componentByteOffset += componentByteLength;
  29638. }
  29639. byteOffset += byteStride;
  29640. }
  29641. }
  29642. };
  29643. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  29644. switch (type) {
  29645. case VertexBuffer.BYTE: {
  29646. var value = dataView.getInt8(byteOffset);
  29647. if (normalized) {
  29648. value = Math.max(value / 127, -1);
  29649. }
  29650. return value;
  29651. }
  29652. case VertexBuffer.UNSIGNED_BYTE: {
  29653. var value = dataView.getUint8(byteOffset);
  29654. if (normalized) {
  29655. value = value / 255;
  29656. }
  29657. return value;
  29658. }
  29659. case VertexBuffer.SHORT: {
  29660. var value = dataView.getInt16(byteOffset, true);
  29661. if (normalized) {
  29662. value = Math.max(value / 16383, -1);
  29663. }
  29664. return value;
  29665. }
  29666. case VertexBuffer.UNSIGNED_SHORT: {
  29667. var value = dataView.getUint16(byteOffset, true);
  29668. if (normalized) {
  29669. value = value / 65535;
  29670. }
  29671. return value;
  29672. }
  29673. case VertexBuffer.FLOAT: {
  29674. return dataView.getFloat32(byteOffset, true);
  29675. }
  29676. default: {
  29677. throw new Error("Invalid component type " + type);
  29678. }
  29679. }
  29680. };
  29681. /**
  29682. * The byte type.
  29683. */
  29684. VertexBuffer.BYTE = 5120;
  29685. /**
  29686. * The unsigned byte type.
  29687. */
  29688. VertexBuffer.UNSIGNED_BYTE = 5121;
  29689. /**
  29690. * The short type.
  29691. */
  29692. VertexBuffer.SHORT = 5122;
  29693. /**
  29694. * The unsigned short type.
  29695. */
  29696. VertexBuffer.UNSIGNED_SHORT = 5123;
  29697. /**
  29698. * The integer type.
  29699. */
  29700. VertexBuffer.INT = 5124;
  29701. /**
  29702. * The unsigned integer type.
  29703. */
  29704. VertexBuffer.UNSIGNED_INT = 5125;
  29705. /**
  29706. * The float type.
  29707. */
  29708. VertexBuffer.FLOAT = 5126;
  29709. // Enums
  29710. VertexBuffer._PositionKind = "position";
  29711. VertexBuffer._NormalKind = "normal";
  29712. VertexBuffer._TangentKind = "tangent";
  29713. VertexBuffer._UVKind = "uv";
  29714. VertexBuffer._UV2Kind = "uv2";
  29715. VertexBuffer._UV3Kind = "uv3";
  29716. VertexBuffer._UV4Kind = "uv4";
  29717. VertexBuffer._UV5Kind = "uv5";
  29718. VertexBuffer._UV6Kind = "uv6";
  29719. VertexBuffer._ColorKind = "color";
  29720. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  29721. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  29722. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  29723. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  29724. return VertexBuffer;
  29725. }());
  29726. BABYLON.VertexBuffer = VertexBuffer;
  29727. })(BABYLON || (BABYLON = {}));
  29728. //# sourceMappingURL=babylon.vertexBuffer.js.map
  29729. var BABYLON;
  29730. (function (BABYLON) {
  29731. /**
  29732. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  29733. */
  29734. var DummyInternalTextureTracker = /** @class */ (function () {
  29735. function DummyInternalTextureTracker() {
  29736. /**
  29737. * Gets or set the previous tracker in the list
  29738. */
  29739. this.previous = null;
  29740. /**
  29741. * Gets or set the next tracker in the list
  29742. */
  29743. this.next = null;
  29744. }
  29745. return DummyInternalTextureTracker;
  29746. }());
  29747. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  29748. })(BABYLON || (BABYLON = {}));
  29749. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  29750. var BABYLON;
  29751. (function (BABYLON) {
  29752. /**
  29753. * Class used to store data associated with WebGL texture data for the engine
  29754. * This class should not be used directly
  29755. */
  29756. var InternalTexture = /** @class */ (function () {
  29757. /**
  29758. * Creates a new InternalTexture
  29759. * @param engine defines the engine to use
  29760. * @param dataSource defines the type of data that will be used
  29761. */
  29762. function InternalTexture(engine, dataSource) {
  29763. /**
  29764. * Observable called when the texture is loaded
  29765. */
  29766. this.onLoadedObservable = new BABYLON.Observable();
  29767. /**
  29768. * Gets or set the previous tracker in the list
  29769. */
  29770. this.previous = null;
  29771. /**
  29772. * Gets or set the next tracker in the list
  29773. */
  29774. this.next = null;
  29775. // Private
  29776. /** @hidden */
  29777. this._initialSlot = -1;
  29778. /** @hidden */
  29779. this._designatedSlot = -1;
  29780. /** @hidden */
  29781. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  29782. /** @hidden */
  29783. this._comparisonFunction = 0;
  29784. /** @hidden */
  29785. this._references = 1;
  29786. this._engine = engine;
  29787. this._dataSource = dataSource;
  29788. this._webGLTexture = engine._createTexture();
  29789. }
  29790. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  29791. /**
  29792. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  29793. */
  29794. get: function () {
  29795. return this._dataSource;
  29796. },
  29797. enumerable: true,
  29798. configurable: true
  29799. });
  29800. /**
  29801. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  29802. */
  29803. InternalTexture.prototype.incrementReferences = function () {
  29804. this._references++;
  29805. };
  29806. /**
  29807. * Change the size of the texture (not the size of the content)
  29808. * @param width defines the new width
  29809. * @param height defines the new height
  29810. * @param depth defines the new depth (1 by default)
  29811. */
  29812. InternalTexture.prototype.updateSize = function (width, height, depth) {
  29813. if (depth === void 0) { depth = 1; }
  29814. this.width = width;
  29815. this.height = height;
  29816. this.depth = depth;
  29817. this.baseWidth = width;
  29818. this.baseHeight = height;
  29819. this.baseDepth = depth;
  29820. this._size = width * height * depth;
  29821. };
  29822. /** @hidden */
  29823. InternalTexture.prototype._rebuild = function () {
  29824. var _this = this;
  29825. var proxy;
  29826. this.isReady = false;
  29827. this._cachedCoordinatesMode = null;
  29828. this._cachedWrapU = null;
  29829. this._cachedWrapV = null;
  29830. this._cachedAnisotropicFilteringLevel = null;
  29831. switch (this._dataSource) {
  29832. case InternalTexture.DATASOURCE_TEMP:
  29833. return;
  29834. case InternalTexture.DATASOURCE_URL:
  29835. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  29836. _this.isReady = true;
  29837. }, null, this._buffer, undefined, this.format);
  29838. proxy._swapAndDie(this);
  29839. return;
  29840. case InternalTexture.DATASOURCE_RAW:
  29841. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29842. proxy._swapAndDie(this);
  29843. this.isReady = true;
  29844. return;
  29845. case InternalTexture.DATASOURCE_RAW3D:
  29846. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29847. proxy._swapAndDie(this);
  29848. this.isReady = true;
  29849. return;
  29850. case InternalTexture.DATASOURCE_DYNAMIC:
  29851. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  29852. proxy._swapAndDie(this);
  29853. // The engine will make sure to update content so no need to flag it as isReady = true
  29854. return;
  29855. case InternalTexture.DATASOURCE_RENDERTARGET:
  29856. var options = new BABYLON.RenderTargetCreationOptions();
  29857. options.generateDepthBuffer = this._generateDepthBuffer;
  29858. options.generateMipMaps = this.generateMipMaps;
  29859. options.generateStencilBuffer = this._generateStencilBuffer;
  29860. options.samplingMode = this.samplingMode;
  29861. options.type = this.type;
  29862. if (this.isCube) {
  29863. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  29864. }
  29865. else {
  29866. var size = {
  29867. width: this.width,
  29868. height: this.height
  29869. };
  29870. proxy = this._engine.createRenderTargetTexture(size, options);
  29871. }
  29872. proxy._swapAndDie(this);
  29873. this.isReady = true;
  29874. return;
  29875. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  29876. var depthTextureOptions = {
  29877. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  29878. comparisonFunction: this._comparisonFunction,
  29879. generateStencil: this._generateStencilBuffer,
  29880. isCube: this.isCube
  29881. };
  29882. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  29883. proxy._swapAndDie(this);
  29884. this.isReady = true;
  29885. return;
  29886. case InternalTexture.DATASOURCE_CUBE:
  29887. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  29888. _this.isReady = true;
  29889. }, null, this.format, this._extension);
  29890. proxy._swapAndDie(this);
  29891. return;
  29892. case InternalTexture.DATASOURCE_CUBERAW:
  29893. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29894. proxy._swapAndDie(this);
  29895. this.isReady = true;
  29896. return;
  29897. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  29898. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  29899. if (proxy) {
  29900. proxy._swapAndDie(_this);
  29901. }
  29902. _this.isReady = true;
  29903. }, null, this.format, this._extension);
  29904. return;
  29905. }
  29906. };
  29907. InternalTexture.prototype._swapAndDie = function (target) {
  29908. target._webGLTexture = this._webGLTexture;
  29909. if (this._framebuffer) {
  29910. target._framebuffer = this._framebuffer;
  29911. }
  29912. if (this._depthStencilBuffer) {
  29913. target._depthStencilBuffer = this._depthStencilBuffer;
  29914. }
  29915. if (this._lodTextureHigh) {
  29916. if (target._lodTextureHigh) {
  29917. target._lodTextureHigh.dispose();
  29918. }
  29919. target._lodTextureHigh = this._lodTextureHigh;
  29920. }
  29921. if (this._lodTextureMid) {
  29922. if (target._lodTextureMid) {
  29923. target._lodTextureMid.dispose();
  29924. }
  29925. target._lodTextureMid = this._lodTextureMid;
  29926. }
  29927. if (this._lodTextureLow) {
  29928. if (target._lodTextureLow) {
  29929. target._lodTextureLow.dispose();
  29930. }
  29931. target._lodTextureLow = this._lodTextureLow;
  29932. }
  29933. var cache = this._engine.getLoadedTexturesCache();
  29934. var index = cache.indexOf(this);
  29935. if (index !== -1) {
  29936. cache.splice(index, 1);
  29937. }
  29938. };
  29939. /**
  29940. * Dispose the current allocated resources
  29941. */
  29942. InternalTexture.prototype.dispose = function () {
  29943. if (!this._webGLTexture) {
  29944. return;
  29945. }
  29946. this._references--;
  29947. if (this._references === 0) {
  29948. this._engine._releaseTexture(this);
  29949. this._webGLTexture = null;
  29950. this.previous = null;
  29951. this.next = null;
  29952. }
  29953. };
  29954. /**
  29955. * The source of the texture data is unknown
  29956. */
  29957. InternalTexture.DATASOURCE_UNKNOWN = 0;
  29958. /**
  29959. * Texture data comes from an URL
  29960. */
  29961. InternalTexture.DATASOURCE_URL = 1;
  29962. /**
  29963. * Texture data is only used for temporary storage
  29964. */
  29965. InternalTexture.DATASOURCE_TEMP = 2;
  29966. /**
  29967. * Texture data comes from raw data (ArrayBuffer)
  29968. */
  29969. InternalTexture.DATASOURCE_RAW = 3;
  29970. /**
  29971. * Texture content is dynamic (video or dynamic texture)
  29972. */
  29973. InternalTexture.DATASOURCE_DYNAMIC = 4;
  29974. /**
  29975. * Texture content is generated by rendering to it
  29976. */
  29977. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  29978. /**
  29979. * Texture content is part of a multi render target process
  29980. */
  29981. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  29982. /**
  29983. * Texture data comes from a cube data file
  29984. */
  29985. InternalTexture.DATASOURCE_CUBE = 7;
  29986. /**
  29987. * Texture data comes from a raw cube data
  29988. */
  29989. InternalTexture.DATASOURCE_CUBERAW = 8;
  29990. /**
  29991. * Texture data come from a prefiltered cube data file
  29992. */
  29993. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  29994. /**
  29995. * Texture content is raw 3D data
  29996. */
  29997. InternalTexture.DATASOURCE_RAW3D = 10;
  29998. /**
  29999. * Texture content is a depth texture
  30000. */
  30001. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  30002. return InternalTexture;
  30003. }());
  30004. BABYLON.InternalTexture = InternalTexture;
  30005. })(BABYLON || (BABYLON = {}));
  30006. //# sourceMappingURL=babylon.internalTexture.js.map
  30007. var BABYLON;
  30008. (function (BABYLON) {
  30009. var BaseTexture = /** @class */ (function () {
  30010. function BaseTexture(scene) {
  30011. this._hasAlpha = false;
  30012. this.getAlphaFromRGB = false;
  30013. this.level = 1;
  30014. this.coordinatesIndex = 0;
  30015. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  30016. /**
  30017. * | Value | Type | Description |
  30018. * | ----- | ------------------ | ----------- |
  30019. * | 0 | CLAMP_ADDRESSMODE | |
  30020. * | 1 | WRAP_ADDRESSMODE | |
  30021. * | 2 | MIRROR_ADDRESSMODE | |
  30022. */
  30023. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30024. /**
  30025. * | Value | Type | Description |
  30026. * | ----- | ------------------ | ----------- |
  30027. * | 0 | CLAMP_ADDRESSMODE | |
  30028. * | 1 | WRAP_ADDRESSMODE | |
  30029. * | 2 | MIRROR_ADDRESSMODE | |
  30030. */
  30031. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30032. /**
  30033. * | Value | Type | Description |
  30034. * | ----- | ------------------ | ----------- |
  30035. * | 0 | CLAMP_ADDRESSMODE | |
  30036. * | 1 | WRAP_ADDRESSMODE | |
  30037. * | 2 | MIRROR_ADDRESSMODE | |
  30038. */
  30039. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  30040. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  30041. this.isCube = false;
  30042. this.is3D = false;
  30043. this.gammaSpace = true;
  30044. this.invertZ = false;
  30045. this.lodLevelInAlpha = false;
  30046. this.lodGenerationOffset = 0.0;
  30047. this.lodGenerationScale = 0.8;
  30048. this.isRenderTarget = false;
  30049. this.animations = new Array();
  30050. /**
  30051. * An event triggered when the texture is disposed.
  30052. */
  30053. this.onDisposeObservable = new BABYLON.Observable();
  30054. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30055. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30056. if (this._scene) {
  30057. this._scene.textures.push(this);
  30058. }
  30059. this._uid = null;
  30060. }
  30061. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  30062. get: function () {
  30063. return this._hasAlpha;
  30064. },
  30065. set: function (value) {
  30066. if (this._hasAlpha === value) {
  30067. return;
  30068. }
  30069. this._hasAlpha = value;
  30070. if (this._scene) {
  30071. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  30072. }
  30073. },
  30074. enumerable: true,
  30075. configurable: true
  30076. });
  30077. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  30078. get: function () {
  30079. return this._coordinatesMode;
  30080. },
  30081. /**
  30082. * How a texture is mapped.
  30083. *
  30084. * | Value | Type | Description |
  30085. * | ----- | ----------------------------------- | ----------- |
  30086. * | 0 | EXPLICIT_MODE | |
  30087. * | 1 | SPHERICAL_MODE | |
  30088. * | 2 | PLANAR_MODE | |
  30089. * | 3 | CUBIC_MODE | |
  30090. * | 4 | PROJECTION_MODE | |
  30091. * | 5 | SKYBOX_MODE | |
  30092. * | 6 | INVCUBIC_MODE | |
  30093. * | 7 | EQUIRECTANGULAR_MODE | |
  30094. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30095. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30096. */
  30097. set: function (value) {
  30098. if (this._coordinatesMode === value) {
  30099. return;
  30100. }
  30101. this._coordinatesMode = value;
  30102. if (this._scene) {
  30103. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30104. }
  30105. },
  30106. enumerable: true,
  30107. configurable: true
  30108. });
  30109. Object.defineProperty(BaseTexture.prototype, "uid", {
  30110. get: function () {
  30111. if (!this._uid) {
  30112. this._uid = BABYLON.Tools.RandomId();
  30113. }
  30114. return this._uid;
  30115. },
  30116. enumerable: true,
  30117. configurable: true
  30118. });
  30119. BaseTexture.prototype.toString = function () {
  30120. return this.name;
  30121. };
  30122. BaseTexture.prototype.getClassName = function () {
  30123. return "BaseTexture";
  30124. };
  30125. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30126. set: function (callback) {
  30127. if (this._onDisposeObserver) {
  30128. this.onDisposeObservable.remove(this._onDisposeObserver);
  30129. }
  30130. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30131. },
  30132. enumerable: true,
  30133. configurable: true
  30134. });
  30135. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30136. get: function () {
  30137. return true;
  30138. },
  30139. enumerable: true,
  30140. configurable: true
  30141. });
  30142. BaseTexture.prototype.getScene = function () {
  30143. return this._scene;
  30144. };
  30145. BaseTexture.prototype.getTextureMatrix = function () {
  30146. return BABYLON.Matrix.IdentityReadOnly;
  30147. };
  30148. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30149. return BABYLON.Matrix.IdentityReadOnly;
  30150. };
  30151. BaseTexture.prototype.getInternalTexture = function () {
  30152. return this._texture;
  30153. };
  30154. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30155. return !this.isBlocking || this.isReady();
  30156. };
  30157. BaseTexture.prototype.isReady = function () {
  30158. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30159. this.delayLoad();
  30160. return false;
  30161. }
  30162. if (this._texture) {
  30163. return this._texture.isReady;
  30164. }
  30165. return false;
  30166. };
  30167. BaseTexture.prototype.getSize = function () {
  30168. if (this._texture && this._texture.width) {
  30169. return new BABYLON.Size(this._texture.width, this._texture.height);
  30170. }
  30171. if (this._texture && this._texture._size) {
  30172. return new BABYLON.Size(this._texture._size, this._texture._size);
  30173. }
  30174. return BABYLON.Size.Zero();
  30175. };
  30176. BaseTexture.prototype.getBaseSize = function () {
  30177. if (!this.isReady() || !this._texture)
  30178. return BABYLON.Size.Zero();
  30179. if (this._texture._size) {
  30180. return new BABYLON.Size(this._texture._size, this._texture._size);
  30181. }
  30182. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30183. };
  30184. BaseTexture.prototype.scale = function (ratio) {
  30185. };
  30186. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30187. get: function () {
  30188. return false;
  30189. },
  30190. enumerable: true,
  30191. configurable: true
  30192. });
  30193. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30194. if (!this._scene) {
  30195. return null;
  30196. }
  30197. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30198. for (var index = 0; index < texturesCache.length; index++) {
  30199. var texturesCacheEntry = texturesCache[index];
  30200. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30201. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30202. texturesCacheEntry.incrementReferences();
  30203. return texturesCacheEntry;
  30204. }
  30205. }
  30206. }
  30207. return null;
  30208. };
  30209. BaseTexture.prototype._rebuild = function () {
  30210. };
  30211. BaseTexture.prototype.delayLoad = function () {
  30212. };
  30213. BaseTexture.prototype.clone = function () {
  30214. return null;
  30215. };
  30216. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30217. get: function () {
  30218. if (!this._texture) {
  30219. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30220. }
  30221. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30222. },
  30223. enumerable: true,
  30224. configurable: true
  30225. });
  30226. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30227. get: function () {
  30228. if (!this._texture) {
  30229. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30230. }
  30231. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30232. },
  30233. enumerable: true,
  30234. configurable: true
  30235. });
  30236. BaseTexture.prototype.readPixels = function (faceIndex) {
  30237. if (faceIndex === void 0) { faceIndex = 0; }
  30238. if (!this._texture) {
  30239. return null;
  30240. }
  30241. var size = this.getSize();
  30242. var scene = this.getScene();
  30243. if (!scene) {
  30244. return null;
  30245. }
  30246. var engine = scene.getEngine();
  30247. if (this._texture.isCube) {
  30248. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  30249. }
  30250. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  30251. };
  30252. BaseTexture.prototype.releaseInternalTexture = function () {
  30253. if (this._texture) {
  30254. this._texture.dispose();
  30255. this._texture = null;
  30256. }
  30257. };
  30258. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30259. get: function () {
  30260. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30261. return null;
  30262. }
  30263. if (!this._texture._sphericalPolynomial) {
  30264. this._texture._sphericalPolynomial =
  30265. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30266. }
  30267. return this._texture._sphericalPolynomial;
  30268. },
  30269. set: function (value) {
  30270. if (this._texture) {
  30271. this._texture._sphericalPolynomial = value;
  30272. }
  30273. },
  30274. enumerable: true,
  30275. configurable: true
  30276. });
  30277. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30278. get: function () {
  30279. if (this._texture) {
  30280. return this._texture._lodTextureHigh;
  30281. }
  30282. return null;
  30283. },
  30284. enumerable: true,
  30285. configurable: true
  30286. });
  30287. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30288. get: function () {
  30289. if (this._texture) {
  30290. return this._texture._lodTextureMid;
  30291. }
  30292. return null;
  30293. },
  30294. enumerable: true,
  30295. configurable: true
  30296. });
  30297. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30298. get: function () {
  30299. if (this._texture) {
  30300. return this._texture._lodTextureLow;
  30301. }
  30302. return null;
  30303. },
  30304. enumerable: true,
  30305. configurable: true
  30306. });
  30307. BaseTexture.prototype.dispose = function () {
  30308. if (!this._scene) {
  30309. return;
  30310. }
  30311. // Animations
  30312. this._scene.stopAnimation(this);
  30313. // Remove from scene
  30314. this._scene._removePendingData(this);
  30315. var index = this._scene.textures.indexOf(this);
  30316. if (index >= 0) {
  30317. this._scene.textures.splice(index, 1);
  30318. }
  30319. if (this._texture === undefined) {
  30320. return;
  30321. }
  30322. // Release
  30323. this.releaseInternalTexture();
  30324. // Callback
  30325. this.onDisposeObservable.notifyObservers(this);
  30326. this.onDisposeObservable.clear();
  30327. };
  30328. BaseTexture.prototype.serialize = function () {
  30329. if (!this.name) {
  30330. return null;
  30331. }
  30332. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30333. // Animations
  30334. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30335. return serializationObject;
  30336. };
  30337. BaseTexture.WhenAllReady = function (textures, callback) {
  30338. var numRemaining = textures.length;
  30339. if (numRemaining === 0) {
  30340. callback();
  30341. return;
  30342. }
  30343. var _loop_1 = function () {
  30344. texture = textures[i];
  30345. if (texture.isReady()) {
  30346. if (--numRemaining === 0) {
  30347. callback();
  30348. }
  30349. }
  30350. else {
  30351. onLoadObservable = texture.onLoadObservable;
  30352. var onLoadCallback_1 = function () {
  30353. onLoadObservable.removeCallback(onLoadCallback_1);
  30354. if (--numRemaining === 0) {
  30355. callback();
  30356. }
  30357. };
  30358. onLoadObservable.add(onLoadCallback_1);
  30359. }
  30360. };
  30361. var texture, onLoadObservable;
  30362. for (var i = 0; i < textures.length; i++) {
  30363. _loop_1();
  30364. }
  30365. };
  30366. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30367. __decorate([
  30368. BABYLON.serialize()
  30369. ], BaseTexture.prototype, "name", void 0);
  30370. __decorate([
  30371. BABYLON.serialize("hasAlpha")
  30372. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30373. __decorate([
  30374. BABYLON.serialize()
  30375. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30376. __decorate([
  30377. BABYLON.serialize()
  30378. ], BaseTexture.prototype, "level", void 0);
  30379. __decorate([
  30380. BABYLON.serialize()
  30381. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30382. __decorate([
  30383. BABYLON.serialize("coordinatesMode")
  30384. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30385. __decorate([
  30386. BABYLON.serialize()
  30387. ], BaseTexture.prototype, "wrapU", void 0);
  30388. __decorate([
  30389. BABYLON.serialize()
  30390. ], BaseTexture.prototype, "wrapV", void 0);
  30391. __decorate([
  30392. BABYLON.serialize()
  30393. ], BaseTexture.prototype, "wrapR", void 0);
  30394. __decorate([
  30395. BABYLON.serialize()
  30396. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30397. __decorate([
  30398. BABYLON.serialize()
  30399. ], BaseTexture.prototype, "isCube", void 0);
  30400. __decorate([
  30401. BABYLON.serialize()
  30402. ], BaseTexture.prototype, "is3D", void 0);
  30403. __decorate([
  30404. BABYLON.serialize()
  30405. ], BaseTexture.prototype, "gammaSpace", void 0);
  30406. __decorate([
  30407. BABYLON.serialize()
  30408. ], BaseTexture.prototype, "invertZ", void 0);
  30409. __decorate([
  30410. BABYLON.serialize()
  30411. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30412. __decorate([
  30413. BABYLON.serialize()
  30414. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  30415. __decorate([
  30416. BABYLON.serialize()
  30417. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  30418. __decorate([
  30419. BABYLON.serialize()
  30420. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30421. return BaseTexture;
  30422. }());
  30423. BABYLON.BaseTexture = BaseTexture;
  30424. })(BABYLON || (BABYLON = {}));
  30425. //# sourceMappingURL=babylon.baseTexture.js.map
  30426. var BABYLON;
  30427. (function (BABYLON) {
  30428. var Texture = /** @class */ (function (_super) {
  30429. __extends(Texture, _super);
  30430. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30431. if (noMipmap === void 0) { noMipmap = false; }
  30432. if (invertY === void 0) { invertY = true; }
  30433. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30434. if (onLoad === void 0) { onLoad = null; }
  30435. if (onError === void 0) { onError = null; }
  30436. if (buffer === void 0) { buffer = null; }
  30437. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30438. var _this = _super.call(this, scene) || this;
  30439. _this.uOffset = 0;
  30440. _this.vOffset = 0;
  30441. _this.uScale = 1.0;
  30442. _this.vScale = 1.0;
  30443. _this.uAng = 0;
  30444. _this.vAng = 0;
  30445. _this.wAng = 0;
  30446. _this._isBlocking = true;
  30447. _this.name = url || "";
  30448. _this.url = url;
  30449. _this._noMipmap = noMipmap;
  30450. _this._invertY = invertY;
  30451. _this._samplingMode = samplingMode;
  30452. _this._buffer = buffer;
  30453. _this._deleteBuffer = deleteBuffer;
  30454. if (format) {
  30455. _this._format = format;
  30456. }
  30457. scene = _this.getScene();
  30458. if (!scene) {
  30459. return _this;
  30460. }
  30461. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30462. var load = function () {
  30463. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30464. _this.onLoadObservable.notifyObservers(_this);
  30465. }
  30466. if (onLoad) {
  30467. onLoad();
  30468. }
  30469. if (!_this.isBlocking && scene) {
  30470. scene.resetCachedMaterial();
  30471. }
  30472. };
  30473. if (!_this.url) {
  30474. _this._delayedOnLoad = load;
  30475. _this._delayedOnError = onError;
  30476. return _this;
  30477. }
  30478. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30479. if (!_this._texture) {
  30480. if (!scene.useDelayedTextureLoading) {
  30481. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30482. if (deleteBuffer) {
  30483. delete _this._buffer;
  30484. }
  30485. }
  30486. else {
  30487. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30488. _this._delayedOnLoad = load;
  30489. _this._delayedOnError = onError;
  30490. }
  30491. }
  30492. else {
  30493. if (_this._texture.isReady) {
  30494. BABYLON.Tools.SetImmediate(function () { return load(); });
  30495. }
  30496. else {
  30497. _this._texture.onLoadedObservable.add(load);
  30498. }
  30499. }
  30500. return _this;
  30501. }
  30502. Object.defineProperty(Texture.prototype, "noMipmap", {
  30503. get: function () {
  30504. return this._noMipmap;
  30505. },
  30506. enumerable: true,
  30507. configurable: true
  30508. });
  30509. Object.defineProperty(Texture.prototype, "isBlocking", {
  30510. get: function () {
  30511. return this._isBlocking;
  30512. },
  30513. set: function (value) {
  30514. this._isBlocking = value;
  30515. },
  30516. enumerable: true,
  30517. configurable: true
  30518. });
  30519. Object.defineProperty(Texture.prototype, "samplingMode", {
  30520. get: function () {
  30521. return this._samplingMode;
  30522. },
  30523. enumerable: true,
  30524. configurable: true
  30525. });
  30526. Texture.prototype.updateURL = function (url) {
  30527. this.url = url;
  30528. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30529. this.delayLoad();
  30530. };
  30531. Texture.prototype.delayLoad = function () {
  30532. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30533. return;
  30534. }
  30535. var scene = this.getScene();
  30536. if (!scene) {
  30537. return;
  30538. }
  30539. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30540. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  30541. if (!this._texture) {
  30542. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  30543. if (this._deleteBuffer) {
  30544. delete this._buffer;
  30545. }
  30546. }
  30547. else {
  30548. if (this._delayedOnLoad) {
  30549. if (this._texture.isReady) {
  30550. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  30551. }
  30552. else {
  30553. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  30554. }
  30555. }
  30556. }
  30557. this._delayedOnLoad = null;
  30558. this._delayedOnError = null;
  30559. };
  30560. Texture.prototype.updateSamplingMode = function (samplingMode) {
  30561. if (!this._texture) {
  30562. return;
  30563. }
  30564. var scene = this.getScene();
  30565. if (!scene) {
  30566. return;
  30567. }
  30568. this._samplingMode = samplingMode;
  30569. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  30570. };
  30571. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  30572. x *= this.uScale;
  30573. y *= this.vScale;
  30574. x -= 0.5 * this.uScale;
  30575. y -= 0.5 * this.vScale;
  30576. z -= 0.5;
  30577. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  30578. t.x += 0.5 * this.uScale + this.uOffset;
  30579. t.y += 0.5 * this.vScale + this.vOffset;
  30580. t.z += 0.5;
  30581. };
  30582. Texture.prototype.getTextureMatrix = function () {
  30583. var _this = this;
  30584. if (this.uOffset === this._cachedUOffset &&
  30585. this.vOffset === this._cachedVOffset &&
  30586. this.uScale === this._cachedUScale &&
  30587. this.vScale === this._cachedVScale &&
  30588. this.uAng === this._cachedUAng &&
  30589. this.vAng === this._cachedVAng &&
  30590. this.wAng === this._cachedWAng) {
  30591. return this._cachedTextureMatrix;
  30592. }
  30593. this._cachedUOffset = this.uOffset;
  30594. this._cachedVOffset = this.vOffset;
  30595. this._cachedUScale = this.uScale;
  30596. this._cachedVScale = this.vScale;
  30597. this._cachedUAng = this.uAng;
  30598. this._cachedVAng = this.vAng;
  30599. this._cachedWAng = this.wAng;
  30600. if (!this._cachedTextureMatrix) {
  30601. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30602. this._rowGenerationMatrix = new BABYLON.Matrix();
  30603. this._t0 = BABYLON.Vector3.Zero();
  30604. this._t1 = BABYLON.Vector3.Zero();
  30605. this._t2 = BABYLON.Vector3.Zero();
  30606. }
  30607. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  30608. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  30609. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  30610. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  30611. this._t1.subtractInPlace(this._t0);
  30612. this._t2.subtractInPlace(this._t0);
  30613. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30614. this._cachedTextureMatrix.m[0] = this._t1.x;
  30615. this._cachedTextureMatrix.m[1] = this._t1.y;
  30616. this._cachedTextureMatrix.m[2] = this._t1.z;
  30617. this._cachedTextureMatrix.m[4] = this._t2.x;
  30618. this._cachedTextureMatrix.m[5] = this._t2.y;
  30619. this._cachedTextureMatrix.m[6] = this._t2.z;
  30620. this._cachedTextureMatrix.m[8] = this._t0.x;
  30621. this._cachedTextureMatrix.m[9] = this._t0.y;
  30622. this._cachedTextureMatrix.m[10] = this._t0.z;
  30623. var scene = this.getScene();
  30624. if (!scene) {
  30625. return this._cachedTextureMatrix;
  30626. }
  30627. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30628. return mat.hasTexture(_this);
  30629. });
  30630. return this._cachedTextureMatrix;
  30631. };
  30632. Texture.prototype.getReflectionTextureMatrix = function () {
  30633. var _this = this;
  30634. var scene = this.getScene();
  30635. if (!scene) {
  30636. return this._cachedTextureMatrix;
  30637. }
  30638. if (this.uOffset === this._cachedUOffset &&
  30639. this.vOffset === this._cachedVOffset &&
  30640. this.uScale === this._cachedUScale &&
  30641. this.vScale === this._cachedVScale &&
  30642. this.coordinatesMode === this._cachedCoordinatesMode) {
  30643. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  30644. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  30645. return this._cachedTextureMatrix;
  30646. }
  30647. }
  30648. else {
  30649. return this._cachedTextureMatrix;
  30650. }
  30651. }
  30652. if (!this._cachedTextureMatrix) {
  30653. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30654. }
  30655. if (!this._projectionModeMatrix) {
  30656. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  30657. }
  30658. this._cachedUOffset = this.uOffset;
  30659. this._cachedVOffset = this.vOffset;
  30660. this._cachedUScale = this.uScale;
  30661. this._cachedVScale = this.vScale;
  30662. this._cachedCoordinatesMode = this.coordinatesMode;
  30663. switch (this.coordinatesMode) {
  30664. case Texture.PLANAR_MODE:
  30665. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30666. this._cachedTextureMatrix[0] = this.uScale;
  30667. this._cachedTextureMatrix[5] = this.vScale;
  30668. this._cachedTextureMatrix[12] = this.uOffset;
  30669. this._cachedTextureMatrix[13] = this.vOffset;
  30670. break;
  30671. case Texture.PROJECTION_MODE:
  30672. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  30673. this._projectionModeMatrix.m[0] = 0.5;
  30674. this._projectionModeMatrix.m[5] = -0.5;
  30675. this._projectionModeMatrix.m[10] = 0.0;
  30676. this._projectionModeMatrix.m[12] = 0.5;
  30677. this._projectionModeMatrix.m[13] = 0.5;
  30678. this._projectionModeMatrix.m[14] = 1.0;
  30679. this._projectionModeMatrix.m[15] = 1.0;
  30680. var projectionMatrix = scene.getProjectionMatrix();
  30681. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  30682. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  30683. break;
  30684. default:
  30685. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30686. break;
  30687. }
  30688. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30689. return (mat.getActiveTextures().indexOf(_this) !== -1);
  30690. });
  30691. return this._cachedTextureMatrix;
  30692. };
  30693. Texture.prototype.clone = function () {
  30694. var _this = this;
  30695. return BABYLON.SerializationHelper.Clone(function () {
  30696. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  30697. }, this);
  30698. };
  30699. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  30700. get: function () {
  30701. if (!this._onLoadObservable) {
  30702. this._onLoadObservable = new BABYLON.Observable();
  30703. }
  30704. return this._onLoadObservable;
  30705. },
  30706. enumerable: true,
  30707. configurable: true
  30708. });
  30709. Texture.prototype.serialize = function () {
  30710. var serializationObject = _super.prototype.serialize.call(this);
  30711. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  30712. serializationObject.base64String = this._buffer;
  30713. serializationObject.name = serializationObject.name.replace("data:", "");
  30714. }
  30715. serializationObject.invertY = this._invertY;
  30716. serializationObject.samplingMode = this.samplingMode;
  30717. return serializationObject;
  30718. };
  30719. Texture.prototype.getClassName = function () {
  30720. return "Texture";
  30721. };
  30722. Texture.prototype.dispose = function () {
  30723. _super.prototype.dispose.call(this);
  30724. if (this.onLoadObservable) {
  30725. this.onLoadObservable.clear();
  30726. this._onLoadObservable = null;
  30727. }
  30728. this._delayedOnLoad = null;
  30729. this._delayedOnError = null;
  30730. };
  30731. // Statics
  30732. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30733. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30734. if (onLoad === void 0) { onLoad = null; }
  30735. if (onError === void 0) { onError = null; }
  30736. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30737. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  30738. };
  30739. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  30740. if (parsedTexture.customType) {
  30741. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  30742. // Update Sampling Mode
  30743. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  30744. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  30745. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  30746. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  30747. }
  30748. }
  30749. return parsedCustomTexture;
  30750. }
  30751. if (parsedTexture.isCube) {
  30752. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  30753. }
  30754. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  30755. return null;
  30756. }
  30757. var texture = BABYLON.SerializationHelper.Parse(function () {
  30758. var generateMipMaps = true;
  30759. if (parsedTexture.noMipmap) {
  30760. generateMipMaps = false;
  30761. }
  30762. if (parsedTexture.mirrorPlane) {
  30763. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30764. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  30765. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  30766. return mirrorTexture;
  30767. }
  30768. else if (parsedTexture.isRenderTarget) {
  30769. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30770. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  30771. return renderTargetTexture;
  30772. }
  30773. else {
  30774. var texture;
  30775. if (parsedTexture.base64String) {
  30776. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  30777. }
  30778. else {
  30779. var url = rootUrl + parsedTexture.name;
  30780. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  30781. url = parsedTexture.url;
  30782. }
  30783. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  30784. }
  30785. return texture;
  30786. }
  30787. }, parsedTexture, scene);
  30788. // Update Sampling Mode
  30789. if (parsedTexture.samplingMode) {
  30790. var sampling = parsedTexture.samplingMode;
  30791. if (texture._samplingMode !== sampling) {
  30792. texture.updateSamplingMode(sampling);
  30793. }
  30794. }
  30795. // Animations
  30796. if (parsedTexture.animations) {
  30797. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  30798. var parsedAnimation = parsedTexture.animations[animationIndex];
  30799. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  30800. }
  30801. }
  30802. return texture;
  30803. };
  30804. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30805. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30806. if (noMipmap === void 0) { noMipmap = false; }
  30807. if (invertY === void 0) { invertY = true; }
  30808. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30809. if (onLoad === void 0) { onLoad = null; }
  30810. if (onError === void 0) { onError = null; }
  30811. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30812. if (name.substr(0, 5) !== "data:") {
  30813. name = "data:" + name;
  30814. }
  30815. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  30816. };
  30817. // Constants
  30818. Texture.NEAREST_SAMPLINGMODE = 1;
  30819. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  30820. Texture.BILINEAR_SAMPLINGMODE = 2;
  30821. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  30822. Texture.TRILINEAR_SAMPLINGMODE = 3;
  30823. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  30824. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  30825. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  30826. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  30827. Texture.NEAREST_LINEAR = 7;
  30828. Texture.NEAREST_NEAREST = 8;
  30829. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  30830. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  30831. Texture.LINEAR_LINEAR = 11;
  30832. Texture.LINEAR_NEAREST = 12;
  30833. Texture.EXPLICIT_MODE = 0;
  30834. Texture.SPHERICAL_MODE = 1;
  30835. Texture.PLANAR_MODE = 2;
  30836. Texture.CUBIC_MODE = 3;
  30837. Texture.PROJECTION_MODE = 4;
  30838. Texture.SKYBOX_MODE = 5;
  30839. Texture.INVCUBIC_MODE = 6;
  30840. Texture.EQUIRECTANGULAR_MODE = 7;
  30841. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  30842. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  30843. Texture.CLAMP_ADDRESSMODE = 0;
  30844. Texture.WRAP_ADDRESSMODE = 1;
  30845. Texture.MIRROR_ADDRESSMODE = 2;
  30846. /**
  30847. * 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
  30848. */
  30849. Texture.UseSerializedUrlIfAny = false;
  30850. __decorate([
  30851. BABYLON.serialize()
  30852. ], Texture.prototype, "url", void 0);
  30853. __decorate([
  30854. BABYLON.serialize()
  30855. ], Texture.prototype, "uOffset", void 0);
  30856. __decorate([
  30857. BABYLON.serialize()
  30858. ], Texture.prototype, "vOffset", void 0);
  30859. __decorate([
  30860. BABYLON.serialize()
  30861. ], Texture.prototype, "uScale", void 0);
  30862. __decorate([
  30863. BABYLON.serialize()
  30864. ], Texture.prototype, "vScale", void 0);
  30865. __decorate([
  30866. BABYLON.serialize()
  30867. ], Texture.prototype, "uAng", void 0);
  30868. __decorate([
  30869. BABYLON.serialize()
  30870. ], Texture.prototype, "vAng", void 0);
  30871. __decorate([
  30872. BABYLON.serialize()
  30873. ], Texture.prototype, "wAng", void 0);
  30874. __decorate([
  30875. BABYLON.serialize()
  30876. ], Texture.prototype, "isBlocking", null);
  30877. return Texture;
  30878. }(BABYLON.BaseTexture));
  30879. BABYLON.Texture = Texture;
  30880. })(BABYLON || (BABYLON = {}));
  30881. //# sourceMappingURL=babylon.texture.js.map
  30882. var BABYLON;
  30883. (function (BABYLON) {
  30884. /**
  30885. * @hidden
  30886. **/
  30887. var _InstancesBatch = /** @class */ (function () {
  30888. function _InstancesBatch() {
  30889. this.mustReturn = false;
  30890. this.visibleInstances = new Array();
  30891. this.renderSelf = new Array();
  30892. }
  30893. return _InstancesBatch;
  30894. }());
  30895. BABYLON._InstancesBatch = _InstancesBatch;
  30896. var Mesh = /** @class */ (function (_super) {
  30897. __extends(Mesh, _super);
  30898. /**
  30899. * @constructor
  30900. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  30901. * @param {Scene} scene The scene to add this mesh to.
  30902. * @param {Node} parent The parent of this mesh, if it has one
  30903. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  30904. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  30905. * When false, achieved by calling a clone(), also passing False.
  30906. * This will make creation of children, recursive.
  30907. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  30908. */
  30909. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  30910. if (scene === void 0) { scene = null; }
  30911. if (parent === void 0) { parent = null; }
  30912. if (source === void 0) { source = null; }
  30913. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  30914. var _this = _super.call(this, name, scene) || this;
  30915. // Events
  30916. /**
  30917. * An event triggered before rendering the mesh
  30918. */
  30919. _this.onBeforeRenderObservable = new BABYLON.Observable();
  30920. /**
  30921. * An event triggered after rendering the mesh
  30922. */
  30923. _this.onAfterRenderObservable = new BABYLON.Observable();
  30924. /**
  30925. * An event triggered before drawing the mesh
  30926. */
  30927. _this.onBeforeDrawObservable = new BABYLON.Observable();
  30928. // Members
  30929. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30930. _this.instances = new Array();
  30931. _this._LODLevels = new Array();
  30932. _this._visibleInstances = {};
  30933. _this._renderIdForInstances = new Array();
  30934. _this._batchCache = new _InstancesBatch();
  30935. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  30936. // Use by builder only to know what orientation were the mesh build in.
  30937. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  30938. _this.overrideMaterialSideOrientation = null;
  30939. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  30940. // Will be used to save a source mesh reference, If any
  30941. _this._source = null;
  30942. scene = _this.getScene();
  30943. if (source) {
  30944. // Source mesh
  30945. _this._source = source;
  30946. // Geometry
  30947. if (source._geometry) {
  30948. source._geometry.applyToMesh(_this);
  30949. }
  30950. // Deep copy
  30951. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  30952. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix", "_source"]);
  30953. // Metadata
  30954. if (source.metadata && source.metadata.clone) {
  30955. _this.metadata = source.metadata.clone();
  30956. }
  30957. else {
  30958. _this.metadata = source.metadata;
  30959. }
  30960. // Tags
  30961. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  30962. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  30963. }
  30964. // Parent
  30965. _this.parent = source.parent;
  30966. // Pivot
  30967. _this.setPivotMatrix(source.getPivotMatrix());
  30968. _this.id = name + "." + source.id;
  30969. // Material
  30970. _this.material = source.material;
  30971. var index;
  30972. if (!doNotCloneChildren) {
  30973. // Children
  30974. var directDescendants = source.getDescendants(true);
  30975. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  30976. var child = directDescendants[index_1];
  30977. if (child.clone) {
  30978. child.clone(name + "." + child.name, _this);
  30979. }
  30980. }
  30981. }
  30982. // Physics clone
  30983. var physicsEngine = _this.getScene().getPhysicsEngine();
  30984. if (clonePhysicsImpostor && physicsEngine) {
  30985. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  30986. if (impostor) {
  30987. _this.physicsImpostor = impostor.clone(_this);
  30988. }
  30989. }
  30990. // Particles
  30991. for (index = 0; index < scene.particleSystems.length; index++) {
  30992. var system = scene.particleSystems[index];
  30993. if (system.emitter === source) {
  30994. system.clone(system.name, _this);
  30995. }
  30996. }
  30997. _this.computeWorldMatrix(true);
  30998. }
  30999. // Parent
  31000. if (parent !== null) {
  31001. _this.parent = parent;
  31002. }
  31003. return _this;
  31004. }
  31005. Object.defineProperty(Mesh, "FRONTSIDE", {
  31006. /**
  31007. * Mesh side orientation : usually the external or front surface
  31008. */
  31009. get: function () {
  31010. return Mesh._FRONTSIDE;
  31011. },
  31012. enumerable: true,
  31013. configurable: true
  31014. });
  31015. Object.defineProperty(Mesh, "BACKSIDE", {
  31016. /**
  31017. * Mesh side orientation : usually the internal or back surface
  31018. */
  31019. get: function () {
  31020. return Mesh._BACKSIDE;
  31021. },
  31022. enumerable: true,
  31023. configurable: true
  31024. });
  31025. Object.defineProperty(Mesh, "DOUBLESIDE", {
  31026. /**
  31027. * Mesh side orientation : both internal and external or front and back surfaces
  31028. */
  31029. get: function () {
  31030. return Mesh._DOUBLESIDE;
  31031. },
  31032. enumerable: true,
  31033. configurable: true
  31034. });
  31035. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  31036. /**
  31037. * Mesh side orientation : by default, `FRONTSIDE`
  31038. */
  31039. get: function () {
  31040. return Mesh._DEFAULTSIDE;
  31041. },
  31042. enumerable: true,
  31043. configurable: true
  31044. });
  31045. Object.defineProperty(Mesh, "NO_CAP", {
  31046. /**
  31047. * Mesh cap setting : no cap
  31048. */
  31049. get: function () {
  31050. return Mesh._NO_CAP;
  31051. },
  31052. enumerable: true,
  31053. configurable: true
  31054. });
  31055. Object.defineProperty(Mesh, "CAP_START", {
  31056. /**
  31057. * Mesh cap setting : one cap at the beginning of the mesh
  31058. */
  31059. get: function () {
  31060. return Mesh._CAP_START;
  31061. },
  31062. enumerable: true,
  31063. configurable: true
  31064. });
  31065. Object.defineProperty(Mesh, "CAP_END", {
  31066. /**
  31067. * Mesh cap setting : one cap at the end of the mesh
  31068. */
  31069. get: function () {
  31070. return Mesh._CAP_END;
  31071. },
  31072. enumerable: true,
  31073. configurable: true
  31074. });
  31075. Object.defineProperty(Mesh, "CAP_ALL", {
  31076. /**
  31077. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  31078. */
  31079. get: function () {
  31080. return Mesh._CAP_ALL;
  31081. },
  31082. enumerable: true,
  31083. configurable: true
  31084. });
  31085. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31086. set: function (callback) {
  31087. if (this._onBeforeDrawObserver) {
  31088. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31089. }
  31090. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31091. },
  31092. enumerable: true,
  31093. configurable: true
  31094. });
  31095. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31096. get: function () {
  31097. return this._morphTargetManager;
  31098. },
  31099. set: function (value) {
  31100. if (this._morphTargetManager === value) {
  31101. return;
  31102. }
  31103. this._morphTargetManager = value;
  31104. this._syncGeometryWithMorphTargetManager();
  31105. },
  31106. enumerable: true,
  31107. configurable: true
  31108. });
  31109. Object.defineProperty(Mesh.prototype, "source", {
  31110. get: function () {
  31111. return this._source;
  31112. },
  31113. enumerable: true,
  31114. configurable: true
  31115. });
  31116. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31117. get: function () {
  31118. return this._unIndexed;
  31119. },
  31120. set: function (value) {
  31121. if (this._unIndexed !== value) {
  31122. this._unIndexed = value;
  31123. this._markSubMeshesAsAttributesDirty();
  31124. }
  31125. },
  31126. enumerable: true,
  31127. configurable: true
  31128. });
  31129. // Methods
  31130. /**
  31131. * Returns the string "Mesh".
  31132. */
  31133. Mesh.prototype.getClassName = function () {
  31134. return "Mesh";
  31135. };
  31136. /**
  31137. * Returns a string.
  31138. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31139. */
  31140. Mesh.prototype.toString = function (fullDetails) {
  31141. var ret = _super.prototype.toString.call(this, fullDetails);
  31142. ret += ", n vertices: " + this.getTotalVertices();
  31143. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31144. if (this.animations) {
  31145. for (var i = 0; i < this.animations.length; i++) {
  31146. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31147. }
  31148. }
  31149. if (fullDetails) {
  31150. if (this._geometry) {
  31151. var ib = this.getIndices();
  31152. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31153. if (vb && ib) {
  31154. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31155. }
  31156. }
  31157. else {
  31158. ret += ", flat shading: UNKNOWN";
  31159. }
  31160. }
  31161. return ret;
  31162. };
  31163. Mesh.prototype._unBindEffect = function () {
  31164. _super.prototype._unBindEffect.call(this);
  31165. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31166. var instance = _a[_i];
  31167. instance._unBindEffect();
  31168. }
  31169. };
  31170. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31171. /**
  31172. * True if the mesh has some Levels Of Details (LOD).
  31173. * Returns a boolean.
  31174. */
  31175. get: function () {
  31176. return this._LODLevels.length > 0;
  31177. },
  31178. enumerable: true,
  31179. configurable: true
  31180. });
  31181. /**
  31182. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  31183. * @returns an array of {BABYLON.MeshLODLevel}
  31184. */
  31185. Mesh.prototype.getLODLevels = function () {
  31186. return this._LODLevels;
  31187. };
  31188. Mesh.prototype._sortLODLevels = function () {
  31189. this._LODLevels.sort(function (a, b) {
  31190. if (a.distance < b.distance) {
  31191. return 1;
  31192. }
  31193. if (a.distance > b.distance) {
  31194. return -1;
  31195. }
  31196. return 0;
  31197. });
  31198. };
  31199. /**
  31200. * Add a mesh as LOD level triggered at the given distance.
  31201. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31202. * @param {number} distance The distance from the center of the object to show this level
  31203. * @param {Mesh} mesh The mesh to be added as LOD level
  31204. * @return {Mesh} This mesh (for chaining)
  31205. */
  31206. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31207. if (mesh && mesh._masterMesh) {
  31208. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31209. return this;
  31210. }
  31211. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31212. this._LODLevels.push(level);
  31213. if (mesh) {
  31214. mesh._masterMesh = this;
  31215. }
  31216. this._sortLODLevels();
  31217. return this;
  31218. };
  31219. /**
  31220. * Returns the LOD level mesh at the passed distance or null if not found.
  31221. * It is related to the method `addLODLevel(distance, mesh)`.
  31222. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31223. * Returns an object Mesh or `null`.
  31224. */
  31225. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31226. for (var index = 0; index < this._LODLevels.length; index++) {
  31227. var level = this._LODLevels[index];
  31228. if (level.distance === distance) {
  31229. return level.mesh;
  31230. }
  31231. }
  31232. return null;
  31233. };
  31234. /**
  31235. * Remove a mesh from the LOD array
  31236. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31237. * @param {Mesh} mesh The mesh to be removed.
  31238. * @return {Mesh} This mesh (for chaining)
  31239. */
  31240. Mesh.prototype.removeLODLevel = function (mesh) {
  31241. for (var index = 0; index < this._LODLevels.length; index++) {
  31242. if (this._LODLevels[index].mesh === mesh) {
  31243. this._LODLevels.splice(index, 1);
  31244. if (mesh) {
  31245. mesh._masterMesh = null;
  31246. }
  31247. }
  31248. }
  31249. this._sortLODLevels();
  31250. return this;
  31251. };
  31252. /**
  31253. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31254. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31255. */
  31256. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31257. if (!this._LODLevels || this._LODLevels.length === 0) {
  31258. return this;
  31259. }
  31260. var bSphere;
  31261. if (boundingSphere) {
  31262. bSphere = boundingSphere;
  31263. }
  31264. else {
  31265. var boundingInfo = this.getBoundingInfo();
  31266. bSphere = boundingInfo.boundingSphere;
  31267. }
  31268. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31269. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31270. if (this.onLODLevelSelection) {
  31271. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31272. }
  31273. return this;
  31274. }
  31275. for (var index = 0; index < this._LODLevels.length; index++) {
  31276. var level = this._LODLevels[index];
  31277. if (level.distance < distanceToCamera) {
  31278. if (level.mesh) {
  31279. level.mesh._preActivate();
  31280. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31281. }
  31282. if (this.onLODLevelSelection) {
  31283. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31284. }
  31285. return level.mesh;
  31286. }
  31287. }
  31288. if (this.onLODLevelSelection) {
  31289. this.onLODLevelSelection(distanceToCamera, this, this);
  31290. }
  31291. return this;
  31292. };
  31293. Object.defineProperty(Mesh.prototype, "geometry", {
  31294. /**
  31295. * Returns the mesh internal Geometry object.
  31296. */
  31297. get: function () {
  31298. return this._geometry;
  31299. },
  31300. enumerable: true,
  31301. configurable: true
  31302. });
  31303. /**
  31304. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31305. */
  31306. Mesh.prototype.getTotalVertices = function () {
  31307. if (this._geometry === null || this._geometry === undefined) {
  31308. return 0;
  31309. }
  31310. return this._geometry.getTotalVertices();
  31311. };
  31312. /**
  31313. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  31314. * 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.
  31315. * You can force the copy with forceCopy === true
  31316. * Returns null if the mesh has no geometry or no vertex buffer.
  31317. * Possible `kind` values :
  31318. * - BABYLON.VertexBuffer.PositionKind
  31319. * - BABYLON.VertexBuffer.UVKind
  31320. * - BABYLON.VertexBuffer.UV2Kind
  31321. * - BABYLON.VertexBuffer.UV3Kind
  31322. * - BABYLON.VertexBuffer.UV4Kind
  31323. * - BABYLON.VertexBuffer.UV5Kind
  31324. * - BABYLON.VertexBuffer.UV6Kind
  31325. * - BABYLON.VertexBuffer.ColorKind
  31326. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31327. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31328. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31329. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31330. */
  31331. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31332. if (!this._geometry) {
  31333. return null;
  31334. }
  31335. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31336. };
  31337. /**
  31338. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  31339. * Returns `null` if the mesh has no geometry.
  31340. * Possible `kind` values :
  31341. * - BABYLON.VertexBuffer.PositionKind
  31342. * - BABYLON.VertexBuffer.UVKind
  31343. * - BABYLON.VertexBuffer.UV2Kind
  31344. * - BABYLON.VertexBuffer.UV3Kind
  31345. * - BABYLON.VertexBuffer.UV4Kind
  31346. * - BABYLON.VertexBuffer.UV5Kind
  31347. * - BABYLON.VertexBuffer.UV6Kind
  31348. * - BABYLON.VertexBuffer.ColorKind
  31349. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31350. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31351. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31352. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31353. */
  31354. Mesh.prototype.getVertexBuffer = function (kind) {
  31355. if (!this._geometry) {
  31356. return null;
  31357. }
  31358. return this._geometry.getVertexBuffer(kind);
  31359. };
  31360. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31361. if (!this._geometry) {
  31362. if (this._delayInfo) {
  31363. return this._delayInfo.indexOf(kind) !== -1;
  31364. }
  31365. return false;
  31366. }
  31367. return this._geometry.isVerticesDataPresent(kind);
  31368. };
  31369. /**
  31370. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31371. * Possible `kind` values :
  31372. * - BABYLON.VertexBuffer.PositionKind
  31373. * - BABYLON.VertexBuffer.UVKind
  31374. * - BABYLON.VertexBuffer.UV2Kind
  31375. * - BABYLON.VertexBuffer.UV3Kind
  31376. * - BABYLON.VertexBuffer.UV4Kind
  31377. * - BABYLON.VertexBuffer.UV5Kind
  31378. * - BABYLON.VertexBuffer.UV6Kind
  31379. * - BABYLON.VertexBuffer.ColorKind
  31380. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31381. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31382. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31383. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31384. */
  31385. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31386. if (!this._geometry) {
  31387. if (this._delayInfo) {
  31388. return this._delayInfo.indexOf(kind) !== -1;
  31389. }
  31390. return false;
  31391. }
  31392. return this._geometry.isVertexBufferUpdatable(kind);
  31393. };
  31394. /**
  31395. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  31396. * Possible `kind` values :
  31397. * - BABYLON.VertexBuffer.PositionKind
  31398. * - BABYLON.VertexBuffer.UVKind
  31399. * - BABYLON.VertexBuffer.UV2Kind
  31400. * - BABYLON.VertexBuffer.UV3Kind
  31401. * - BABYLON.VertexBuffer.UV4Kind
  31402. * - BABYLON.VertexBuffer.UV5Kind
  31403. * - BABYLON.VertexBuffer.UV6Kind
  31404. * - BABYLON.VertexBuffer.ColorKind
  31405. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31406. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31407. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31408. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31409. */
  31410. Mesh.prototype.getVerticesDataKinds = function () {
  31411. if (!this._geometry) {
  31412. var result = new Array();
  31413. if (this._delayInfo) {
  31414. this._delayInfo.forEach(function (kind, index, array) {
  31415. result.push(kind);
  31416. });
  31417. }
  31418. return result;
  31419. }
  31420. return this._geometry.getVerticesDataKinds();
  31421. };
  31422. /**
  31423. * Returns a positive integer : the total number of indices in this mesh geometry.
  31424. * Returns zero if the mesh has no geometry.
  31425. */
  31426. Mesh.prototype.getTotalIndices = function () {
  31427. if (!this._geometry) {
  31428. return 0;
  31429. }
  31430. return this._geometry.getTotalIndices();
  31431. };
  31432. /**
  31433. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31434. * 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.
  31435. * Returns an empty array if the mesh has no geometry.
  31436. */
  31437. Mesh.prototype.getIndices = function (copyWhenShared) {
  31438. if (!this._geometry) {
  31439. return [];
  31440. }
  31441. return this._geometry.getIndices(copyWhenShared);
  31442. };
  31443. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31444. get: function () {
  31445. return this._masterMesh !== null && this._masterMesh !== undefined;
  31446. },
  31447. enumerable: true,
  31448. configurable: true
  31449. });
  31450. /**
  31451. * Determine if the current mesh is ready to be rendered
  31452. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31453. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31454. * @returns true if all associated assets are ready (material, textures, shaders)
  31455. */
  31456. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31457. if (completeCheck === void 0) { completeCheck = false; }
  31458. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31459. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31460. return false;
  31461. }
  31462. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31463. return false;
  31464. }
  31465. if (!this.subMeshes || this.subMeshes.length === 0) {
  31466. return true;
  31467. }
  31468. if (!completeCheck) {
  31469. return true;
  31470. }
  31471. var engine = this.getEngine();
  31472. var scene = this.getScene();
  31473. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31474. this.computeWorldMatrix();
  31475. var mat = this.material || scene.defaultMaterial;
  31476. if (mat) {
  31477. if (mat.storeEffectOnSubMeshes) {
  31478. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31479. var subMesh = _a[_i];
  31480. var effectiveMaterial = subMesh.getMaterial();
  31481. if (effectiveMaterial) {
  31482. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31483. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31484. return false;
  31485. }
  31486. }
  31487. else {
  31488. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31489. return false;
  31490. }
  31491. }
  31492. }
  31493. }
  31494. }
  31495. else {
  31496. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31497. return false;
  31498. }
  31499. }
  31500. }
  31501. // Shadows
  31502. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31503. var light = _c[_b];
  31504. var generator = light.getShadowGenerator();
  31505. if (generator) {
  31506. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31507. var subMesh = _e[_d];
  31508. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31509. return false;
  31510. }
  31511. }
  31512. }
  31513. }
  31514. // LOD
  31515. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31516. var lod = _g[_f];
  31517. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31518. return false;
  31519. }
  31520. }
  31521. return true;
  31522. };
  31523. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31524. /**
  31525. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  31526. * This property is pertinent only for updatable parametric shapes.
  31527. */
  31528. get: function () {
  31529. return this._areNormalsFrozen;
  31530. },
  31531. enumerable: true,
  31532. configurable: true
  31533. });
  31534. /**
  31535. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31536. * It has no effect at all on other shapes.
  31537. * It prevents the mesh normals from being recomputed on next `positions` array update.
  31538. * Returns the Mesh.
  31539. */
  31540. Mesh.prototype.freezeNormals = function () {
  31541. this._areNormalsFrozen = true;
  31542. return this;
  31543. };
  31544. /**
  31545. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31546. * It has no effect at all on other shapes.
  31547. * It reactivates the mesh normals computation if it was previously frozen.
  31548. * Returns the Mesh.
  31549. */
  31550. Mesh.prototype.unfreezeNormals = function () {
  31551. this._areNormalsFrozen = false;
  31552. return this;
  31553. };
  31554. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  31555. /**
  31556. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  31557. */
  31558. set: function (count) {
  31559. this._overridenInstanceCount = count;
  31560. },
  31561. enumerable: true,
  31562. configurable: true
  31563. });
  31564. // Methods
  31565. Mesh.prototype._preActivate = function () {
  31566. var sceneRenderId = this.getScene().getRenderId();
  31567. if (this._preActivateId === sceneRenderId) {
  31568. return this;
  31569. }
  31570. this._preActivateId = sceneRenderId;
  31571. this._visibleInstances = null;
  31572. return this;
  31573. };
  31574. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  31575. if (this._visibleInstances) {
  31576. this._visibleInstances.intermediateDefaultRenderId = renderId;
  31577. }
  31578. return this;
  31579. };
  31580. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  31581. if (!this._visibleInstances) {
  31582. this._visibleInstances = {};
  31583. this._visibleInstances.defaultRenderId = renderId;
  31584. this._visibleInstances.selfDefaultRenderId = this._renderId;
  31585. }
  31586. if (!this._visibleInstances[renderId]) {
  31587. this._visibleInstances[renderId] = new Array();
  31588. }
  31589. this._visibleInstances[renderId].push(instance);
  31590. return this;
  31591. };
  31592. /**
  31593. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  31594. * This means the mesh underlying bounding box and sphere are recomputed.
  31595. * Returns the Mesh.
  31596. */
  31597. Mesh.prototype.refreshBoundingInfo = function () {
  31598. return this._refreshBoundingInfo(false);
  31599. };
  31600. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  31601. if (this._boundingInfo && this._boundingInfo.isLocked) {
  31602. return this;
  31603. }
  31604. var data = this._getPositionData(applySkeleton);
  31605. if (data) {
  31606. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  31607. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  31608. }
  31609. if (this.subMeshes) {
  31610. for (var index = 0; index < this.subMeshes.length; index++) {
  31611. this.subMeshes[index].refreshBoundingInfo();
  31612. }
  31613. }
  31614. this._updateBoundingInfo();
  31615. return this;
  31616. };
  31617. Mesh.prototype._getPositionData = function (applySkeleton) {
  31618. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31619. if (data && applySkeleton && this.skeleton) {
  31620. data = BABYLON.Tools.Slice(data);
  31621. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31622. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31623. if (matricesWeightsData && matricesIndicesData) {
  31624. var needExtras = this.numBoneInfluencers > 4;
  31625. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  31626. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  31627. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  31628. var tempVector = BABYLON.Tmp.Vector3[0];
  31629. var finalMatrix = BABYLON.Tmp.Matrix[0];
  31630. var tempMatrix = BABYLON.Tmp.Matrix[1];
  31631. var matWeightIdx = 0;
  31632. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  31633. finalMatrix.reset();
  31634. var inf;
  31635. var weight;
  31636. for (inf = 0; inf < 4; inf++) {
  31637. weight = matricesWeightsData[matWeightIdx + inf];
  31638. if (weight <= 0)
  31639. break;
  31640. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31641. finalMatrix.addToSelf(tempMatrix);
  31642. }
  31643. if (needExtras) {
  31644. for (inf = 0; inf < 4; inf++) {
  31645. weight = matricesWeightsExtraData[matWeightIdx + inf];
  31646. if (weight <= 0)
  31647. break;
  31648. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31649. finalMatrix.addToSelf(tempMatrix);
  31650. }
  31651. }
  31652. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  31653. tempVector.toArray(data, index);
  31654. }
  31655. }
  31656. }
  31657. return data;
  31658. };
  31659. Mesh.prototype._createGlobalSubMesh = function (force) {
  31660. var totalVertices = this.getTotalVertices();
  31661. if (!totalVertices || !this.getIndices()) {
  31662. return null;
  31663. }
  31664. // Check if we need to recreate the submeshes
  31665. if (this.subMeshes && this.subMeshes.length > 0) {
  31666. var ib = this.getIndices();
  31667. if (!ib) {
  31668. return null;
  31669. }
  31670. var totalIndices = ib.length;
  31671. var needToRecreate = false;
  31672. if (force) {
  31673. needToRecreate = true;
  31674. }
  31675. else {
  31676. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31677. var submesh = _a[_i];
  31678. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  31679. needToRecreate = true;
  31680. break;
  31681. }
  31682. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  31683. needToRecreate = true;
  31684. break;
  31685. }
  31686. }
  31687. }
  31688. if (!needToRecreate) {
  31689. return this.subMeshes[0];
  31690. }
  31691. }
  31692. this.releaseSubMeshes();
  31693. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  31694. };
  31695. Mesh.prototype.subdivide = function (count) {
  31696. if (count < 1) {
  31697. return;
  31698. }
  31699. var totalIndices = this.getTotalIndices();
  31700. var subdivisionSize = (totalIndices / count) | 0;
  31701. var offset = 0;
  31702. // Ensure that subdivisionSize is a multiple of 3
  31703. while (subdivisionSize % 3 !== 0) {
  31704. subdivisionSize++;
  31705. }
  31706. this.releaseSubMeshes();
  31707. for (var index = 0; index < count; index++) {
  31708. if (offset >= totalIndices) {
  31709. break;
  31710. }
  31711. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  31712. offset += subdivisionSize;
  31713. }
  31714. this.synchronizeInstances();
  31715. };
  31716. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31717. if (updatable === void 0) { updatable = false; }
  31718. if (!this._geometry) {
  31719. var vertexData = new BABYLON.VertexData();
  31720. vertexData.set(data, kind);
  31721. var scene = this.getScene();
  31722. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31723. }
  31724. else {
  31725. this._geometry.setVerticesData(kind, data, updatable, stride);
  31726. }
  31727. return this;
  31728. };
  31729. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  31730. if (updatable === void 0) { updatable = true; }
  31731. var vb = this.getVertexBuffer(kind);
  31732. if (!vb || vb.isUpdatable() === updatable) {
  31733. return;
  31734. }
  31735. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  31736. };
  31737. /**
  31738. * Sets the mesh VertexBuffer.
  31739. * Returns the Mesh.
  31740. */
  31741. Mesh.prototype.setVerticesBuffer = function (buffer) {
  31742. if (!this._geometry) {
  31743. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  31744. }
  31745. this._geometry.setVerticesBuffer(buffer);
  31746. return this;
  31747. };
  31748. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  31749. if (!this._geometry) {
  31750. return this;
  31751. }
  31752. if (!makeItUnique) {
  31753. this._geometry.updateVerticesData(kind, data, updateExtends);
  31754. }
  31755. else {
  31756. this.makeGeometryUnique();
  31757. this.updateVerticesData(kind, data, updateExtends, false);
  31758. }
  31759. return this;
  31760. };
  31761. /**
  31762. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  31763. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  31764. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  31765. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  31766. * Returns the Mesh.
  31767. */
  31768. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  31769. if (computeNormals === void 0) { computeNormals = true; }
  31770. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31771. if (!positions) {
  31772. return this;
  31773. }
  31774. positionFunction(positions);
  31775. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  31776. if (computeNormals) {
  31777. var indices = this.getIndices();
  31778. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31779. if (!normals) {
  31780. return this;
  31781. }
  31782. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  31783. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  31784. }
  31785. return this;
  31786. };
  31787. /**
  31788. * Creates a un-shared specific occurence of the geometry for the mesh.
  31789. * Returns the Mesh.
  31790. */
  31791. Mesh.prototype.makeGeometryUnique = function () {
  31792. if (!this._geometry) {
  31793. return this;
  31794. }
  31795. var oldGeometry = this._geometry;
  31796. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  31797. oldGeometry.releaseForMesh(this, true);
  31798. geometry.applyToMesh(this);
  31799. return this;
  31800. };
  31801. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  31802. if (totalVertices === void 0) { totalVertices = null; }
  31803. if (updatable === void 0) { updatable = false; }
  31804. if (!this._geometry) {
  31805. var vertexData = new BABYLON.VertexData();
  31806. vertexData.indices = indices;
  31807. var scene = this.getScene();
  31808. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31809. }
  31810. else {
  31811. this._geometry.setIndices(indices, totalVertices, updatable);
  31812. }
  31813. return this;
  31814. };
  31815. /**
  31816. * Update the current index buffer
  31817. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  31818. * Returns the Mesh.
  31819. */
  31820. Mesh.prototype.updateIndices = function (indices, offset) {
  31821. if (!this._geometry) {
  31822. return this;
  31823. }
  31824. this._geometry.updateIndices(indices, offset);
  31825. return this;
  31826. };
  31827. /**
  31828. * Invert the geometry to move from a right handed system to a left handed one.
  31829. * Returns the Mesh.
  31830. */
  31831. Mesh.prototype.toLeftHanded = function () {
  31832. if (!this._geometry) {
  31833. return this;
  31834. }
  31835. this._geometry.toLeftHanded();
  31836. return this;
  31837. };
  31838. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  31839. if (!this._geometry) {
  31840. return this;
  31841. }
  31842. var engine = this.getScene().getEngine();
  31843. // Wireframe
  31844. var indexToBind;
  31845. if (this._unIndexed) {
  31846. indexToBind = null;
  31847. }
  31848. else {
  31849. switch (fillMode) {
  31850. case BABYLON.Material.PointFillMode:
  31851. indexToBind = null;
  31852. break;
  31853. case BABYLON.Material.WireFrameFillMode:
  31854. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  31855. break;
  31856. default:
  31857. case BABYLON.Material.TriangleFillMode:
  31858. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  31859. break;
  31860. }
  31861. }
  31862. // VBOs
  31863. this._geometry._bind(effect, indexToBind);
  31864. return this;
  31865. };
  31866. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  31867. if (alternate === void 0) { alternate = false; }
  31868. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  31869. return this;
  31870. }
  31871. this.onBeforeDrawObservable.notifyObservers(this);
  31872. var scene = this.getScene();
  31873. var engine = scene.getEngine();
  31874. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  31875. // or triangles as points
  31876. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  31877. }
  31878. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  31879. // Triangles as wireframe
  31880. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  31881. }
  31882. else {
  31883. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  31884. }
  31885. if (scene._isAlternateRenderingEnabled && !alternate) {
  31886. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  31887. if (!effect || !scene.activeCamera) {
  31888. return this;
  31889. }
  31890. scene._switchToAlternateCameraConfiguration(true);
  31891. this._effectiveMaterial.bindView(effect);
  31892. this._effectiveMaterial.bindViewProjection(effect);
  31893. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  31894. this._draw(subMesh, fillMode, instancesCount, true);
  31895. engine.setViewport(scene.activeCamera.viewport);
  31896. scene._switchToAlternateCameraConfiguration(false);
  31897. this._effectiveMaterial.bindView(effect);
  31898. this._effectiveMaterial.bindViewProjection(effect);
  31899. }
  31900. return this;
  31901. };
  31902. /**
  31903. * Registers for this mesh a javascript function called just before the rendering process.
  31904. * This function is passed the current mesh.
  31905. * Return the Mesh.
  31906. */
  31907. Mesh.prototype.registerBeforeRender = function (func) {
  31908. this.onBeforeRenderObservable.add(func);
  31909. return this;
  31910. };
  31911. /**
  31912. * Disposes a previously registered javascript function called before the rendering.
  31913. * This function is passed the current mesh.
  31914. * Returns the Mesh.
  31915. */
  31916. Mesh.prototype.unregisterBeforeRender = function (func) {
  31917. this.onBeforeRenderObservable.removeCallback(func);
  31918. return this;
  31919. };
  31920. /**
  31921. * Registers for this mesh a javascript function called just after the rendering is complete.
  31922. * This function is passed the current mesh.
  31923. * Returns the Mesh.
  31924. */
  31925. Mesh.prototype.registerAfterRender = function (func) {
  31926. this.onAfterRenderObservable.add(func);
  31927. return this;
  31928. };
  31929. /**
  31930. * Disposes a previously registered javascript function called after the rendering.
  31931. * This function is passed the current mesh.
  31932. * Return the Mesh.
  31933. */
  31934. Mesh.prototype.unregisterAfterRender = function (func) {
  31935. this.onAfterRenderObservable.removeCallback(func);
  31936. return this;
  31937. };
  31938. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  31939. var scene = this.getScene();
  31940. this._batchCache.mustReturn = false;
  31941. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  31942. this._batchCache.visibleInstances[subMeshId] = null;
  31943. if (this._visibleInstances) {
  31944. var currentRenderId = scene.getRenderId();
  31945. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  31946. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  31947. var selfRenderId = this._renderId;
  31948. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  31949. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  31950. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  31951. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  31952. }
  31953. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  31954. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  31955. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  31956. this._batchCache.mustReturn = true;
  31957. return this._batchCache;
  31958. }
  31959. if (currentRenderId !== selfRenderId) {
  31960. this._batchCache.renderSelf[subMeshId] = false;
  31961. }
  31962. }
  31963. this._renderIdForInstances[subMeshId] = currentRenderId;
  31964. }
  31965. return this._batchCache;
  31966. };
  31967. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  31968. var visibleInstances = batch.visibleInstances[subMesh._id];
  31969. if (!visibleInstances) {
  31970. return this;
  31971. }
  31972. var matricesCount = visibleInstances.length + 1;
  31973. var bufferSize = matricesCount * 16 * 4;
  31974. var currentInstancesBufferSize = this._instancesBufferSize;
  31975. var instancesBuffer = this._instancesBuffer;
  31976. while (this._instancesBufferSize < bufferSize) {
  31977. this._instancesBufferSize *= 2;
  31978. }
  31979. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  31980. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  31981. }
  31982. var offset = 0;
  31983. var instancesCount = 0;
  31984. var world = this.getWorldMatrix();
  31985. if (batch.renderSelf[subMesh._id]) {
  31986. world.copyToArray(this._instancesData, offset);
  31987. offset += 16;
  31988. instancesCount++;
  31989. }
  31990. if (visibleInstances) {
  31991. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  31992. var instance = visibleInstances[instanceIndex];
  31993. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  31994. offset += 16;
  31995. instancesCount++;
  31996. }
  31997. }
  31998. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  31999. if (instancesBuffer) {
  32000. instancesBuffer.dispose();
  32001. }
  32002. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  32003. this._instancesBuffer = instancesBuffer;
  32004. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  32005. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  32006. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  32007. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  32008. }
  32009. else {
  32010. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  32011. }
  32012. this._bind(subMesh, effect, fillMode);
  32013. this._draw(subMesh, fillMode, instancesCount);
  32014. engine.unbindInstanceAttributes();
  32015. return this;
  32016. };
  32017. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  32018. var scene = this.getScene();
  32019. var engine = scene.getEngine();
  32020. if (hardwareInstancedRendering) {
  32021. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  32022. }
  32023. else {
  32024. if (batch.renderSelf[subMesh._id]) {
  32025. // Draw
  32026. if (onBeforeDraw) {
  32027. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  32028. }
  32029. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  32030. }
  32031. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  32032. if (visibleInstancesForSubMesh) {
  32033. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  32034. var instance = visibleInstancesForSubMesh[instanceIndex];
  32035. // World
  32036. var world = instance.getWorldMatrix();
  32037. if (onBeforeDraw) {
  32038. onBeforeDraw(true, world, effectiveMaterial);
  32039. }
  32040. // Draw
  32041. this._draw(subMesh, fillMode);
  32042. }
  32043. }
  32044. }
  32045. return this;
  32046. };
  32047. /**
  32048. * Triggers the draw call for the mesh.
  32049. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  32050. * Returns the Mesh.
  32051. */
  32052. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  32053. this._checkOcclusionQuery();
  32054. if (this._isOccluded) {
  32055. return this;
  32056. }
  32057. var scene = this.getScene();
  32058. // Managing instances
  32059. var batch = this._getInstancesRenderList(subMesh._id);
  32060. if (batch.mustReturn) {
  32061. return this;
  32062. }
  32063. // Checking geometry state
  32064. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32065. return this;
  32066. }
  32067. this.onBeforeRenderObservable.notifyObservers(this);
  32068. var engine = scene.getEngine();
  32069. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32070. // Material
  32071. var material = subMesh.getMaterial();
  32072. if (!material) {
  32073. return this;
  32074. }
  32075. this._effectiveMaterial = material;
  32076. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32077. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32078. return this;
  32079. }
  32080. }
  32081. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32082. return this;
  32083. }
  32084. // Alpha mode
  32085. if (enableAlphaMode) {
  32086. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32087. }
  32088. // Outline - step 1
  32089. var savedDepthWrite = engine.getDepthWrite();
  32090. if (this.renderOutline) {
  32091. engine.setDepthWrite(false);
  32092. scene.getOutlineRenderer().render(subMesh, batch);
  32093. engine.setDepthWrite(savedDepthWrite);
  32094. }
  32095. var effect;
  32096. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32097. effect = subMesh.effect;
  32098. }
  32099. else {
  32100. effect = this._effectiveMaterial.getEffect();
  32101. }
  32102. if (!effect) {
  32103. return this;
  32104. }
  32105. var sideOrientation = this.overrideMaterialSideOrientation;
  32106. if (sideOrientation == null) {
  32107. sideOrientation = this._effectiveMaterial.sideOrientation;
  32108. if (this._getWorldMatrixDeterminant() < 0) {
  32109. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32110. }
  32111. }
  32112. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32113. if (this._effectiveMaterial.forceDepthWrite) {
  32114. engine.setDepthWrite(true);
  32115. }
  32116. // Bind
  32117. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32118. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32119. this._bind(subMesh, effect, fillMode);
  32120. }
  32121. var world = this.getWorldMatrix();
  32122. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32123. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32124. }
  32125. else {
  32126. this._effectiveMaterial.bind(world, this);
  32127. }
  32128. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32129. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32130. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32131. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32132. }
  32133. // Draw
  32134. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32135. // Unbind
  32136. this._effectiveMaterial.unbind();
  32137. // Outline - step 2
  32138. if (this.renderOutline && savedDepthWrite) {
  32139. engine.setDepthWrite(true);
  32140. engine.setColorWrite(false);
  32141. scene.getOutlineRenderer().render(subMesh, batch);
  32142. engine.setColorWrite(true);
  32143. }
  32144. // Overlay
  32145. if (this.renderOverlay) {
  32146. var currentMode = engine.getAlphaMode();
  32147. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32148. scene.getOutlineRenderer().render(subMesh, batch, true);
  32149. engine.setAlphaMode(currentMode);
  32150. }
  32151. this.onAfterRenderObservable.notifyObservers(this);
  32152. return this;
  32153. };
  32154. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32155. if (isInstance && effectiveMaterial) {
  32156. effectiveMaterial.bindOnlyWorldMatrix(world);
  32157. }
  32158. };
  32159. /**
  32160. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  32161. */
  32162. Mesh.prototype.getEmittedParticleSystems = function () {
  32163. var results = new Array();
  32164. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32165. var particleSystem = this.getScene().particleSystems[index];
  32166. if (particleSystem.emitter === this) {
  32167. results.push(particleSystem);
  32168. }
  32169. }
  32170. return results;
  32171. };
  32172. /**
  32173. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  32174. */
  32175. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  32176. var results = new Array();
  32177. var descendants = this.getDescendants();
  32178. descendants.push(this);
  32179. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32180. var particleSystem = this.getScene().particleSystems[index];
  32181. var emitter = particleSystem.emitter;
  32182. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  32183. results.push(particleSystem);
  32184. }
  32185. }
  32186. return results;
  32187. };
  32188. /**
  32189. * Normalize matrix weights so that all vertices have a total weight set to 1
  32190. */
  32191. Mesh.prototype.cleanMatrixWeights = function () {
  32192. var epsilon = 1e-3;
  32193. var noInfluenceBoneIndex = 0.0;
  32194. if (this.skeleton) {
  32195. noInfluenceBoneIndex = this.skeleton.bones.length;
  32196. }
  32197. else {
  32198. return;
  32199. }
  32200. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32201. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32202. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32203. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  32204. var influencers = this.numBoneInfluencers;
  32205. var size = matricesWeights.length;
  32206. for (var i = 0; i < size; i += 4) {
  32207. var weight = 0.0;
  32208. var firstZeroWeight = -1;
  32209. for (var j = 0; j < 4; j++) {
  32210. var w = matricesWeights[i + j];
  32211. weight += w;
  32212. if (w < epsilon && firstZeroWeight < 0) {
  32213. firstZeroWeight = j;
  32214. }
  32215. }
  32216. if (matricesWeightsExtra) {
  32217. for (var j = 0; j < 4; j++) {
  32218. var w = matricesWeightsExtra[i + j];
  32219. weight += w;
  32220. if (w < epsilon && firstZeroWeight < 0) {
  32221. firstZeroWeight = j + 4;
  32222. }
  32223. }
  32224. }
  32225. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32226. firstZeroWeight = influencers - 1;
  32227. }
  32228. if (weight > epsilon) {
  32229. var mweight = 1.0 / weight;
  32230. for (var j = 0; j < 4; j++) {
  32231. matricesWeights[i + j] *= mweight;
  32232. }
  32233. if (matricesWeightsExtra) {
  32234. for (var j = 0; j < 4; j++) {
  32235. matricesWeightsExtra[i + j] *= mweight;
  32236. }
  32237. }
  32238. }
  32239. else {
  32240. if (firstZeroWeight >= 4) {
  32241. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32242. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32243. }
  32244. else {
  32245. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32246. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32247. }
  32248. }
  32249. }
  32250. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32251. if (matricesIndicesExtra) {
  32252. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32253. }
  32254. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  32255. if (matricesWeightsExtra) {
  32256. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  32257. }
  32258. };
  32259. Mesh.prototype._checkDelayState = function () {
  32260. var scene = this.getScene();
  32261. if (this._geometry) {
  32262. this._geometry.load(scene);
  32263. }
  32264. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32265. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32266. this._queueLoad(scene);
  32267. }
  32268. return this;
  32269. };
  32270. Mesh.prototype._queueLoad = function (scene) {
  32271. var _this = this;
  32272. scene._addPendingData(this);
  32273. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32274. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32275. if (data instanceof ArrayBuffer) {
  32276. _this._delayLoadingFunction(data, _this);
  32277. }
  32278. else {
  32279. _this._delayLoadingFunction(JSON.parse(data), _this);
  32280. }
  32281. _this.instances.forEach(function (instance) {
  32282. instance._syncSubMeshes();
  32283. });
  32284. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32285. scene._removePendingData(_this);
  32286. }, function () { }, scene.database, getBinaryData);
  32287. return this;
  32288. };
  32289. /**
  32290. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  32291. */
  32292. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32293. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32294. return false;
  32295. }
  32296. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32297. return false;
  32298. }
  32299. this._checkDelayState();
  32300. return true;
  32301. };
  32302. /**
  32303. * Sets the mesh material by the material or multiMaterial `id` property.
  32304. * The material `id` is a string identifying the material or the multiMaterial.
  32305. * This method returns the Mesh.
  32306. */
  32307. Mesh.prototype.setMaterialByID = function (id) {
  32308. var materials = this.getScene().materials;
  32309. var index;
  32310. for (index = materials.length - 1; index > -1; index--) {
  32311. if (materials[index].id === id) {
  32312. this.material = materials[index];
  32313. return this;
  32314. }
  32315. }
  32316. // Multi
  32317. var multiMaterials = this.getScene().multiMaterials;
  32318. for (index = multiMaterials.length - 1; index > -1; index--) {
  32319. if (multiMaterials[index].id === id) {
  32320. this.material = multiMaterials[index];
  32321. return this;
  32322. }
  32323. }
  32324. return this;
  32325. };
  32326. /**
  32327. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32328. */
  32329. Mesh.prototype.getAnimatables = function () {
  32330. var results = new Array();
  32331. if (this.material) {
  32332. results.push(this.material);
  32333. }
  32334. if (this.skeleton) {
  32335. results.push(this.skeleton);
  32336. }
  32337. return results;
  32338. };
  32339. /**
  32340. * Modifies the mesh geometry according to the passed transformation matrix.
  32341. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32342. * The mesh normals are modified accordingly the same transformation.
  32343. * tuto : http://doc.babylonjs.com/resources/baking_transformations
  32344. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32345. * Returns the Mesh.
  32346. */
  32347. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32348. // Position
  32349. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32350. return this;
  32351. }
  32352. var submeshes = this.subMeshes.splice(0);
  32353. this._resetPointsArrayCache();
  32354. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32355. var temp = new Array();
  32356. var index;
  32357. for (index = 0; index < data.length; index += 3) {
  32358. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32359. }
  32360. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32361. // Normals
  32362. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32363. return this;
  32364. }
  32365. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32366. temp = [];
  32367. for (index = 0; index < data.length; index += 3) {
  32368. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32369. }
  32370. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32371. // flip faces?
  32372. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32373. this.flipFaces();
  32374. }
  32375. // Restore submeshes
  32376. this.releaseSubMeshes();
  32377. this.subMeshes = submeshes;
  32378. return this;
  32379. };
  32380. /**
  32381. * Modifies the mesh geometry according to its own current World Matrix.
  32382. * The mesh World Matrix is then reset.
  32383. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32384. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  32385. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32386. * Returns the Mesh.
  32387. */
  32388. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32389. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32390. this.scaling.copyFromFloats(1, 1, 1);
  32391. this.position.copyFromFloats(0, 0, 0);
  32392. this.rotation.copyFromFloats(0, 0, 0);
  32393. //only if quaternion is already set
  32394. if (this.rotationQuaternion) {
  32395. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32396. }
  32397. this._worldMatrix = BABYLON.Matrix.Identity();
  32398. return this;
  32399. };
  32400. Object.defineProperty(Mesh.prototype, "_positions", {
  32401. // Cache
  32402. get: function () {
  32403. if (this._geometry) {
  32404. return this._geometry._positions;
  32405. }
  32406. return null;
  32407. },
  32408. enumerable: true,
  32409. configurable: true
  32410. });
  32411. Mesh.prototype._resetPointsArrayCache = function () {
  32412. if (this._geometry) {
  32413. this._geometry._resetPointsArrayCache();
  32414. }
  32415. return this;
  32416. };
  32417. Mesh.prototype._generatePointsArray = function () {
  32418. if (this._geometry) {
  32419. return this._geometry._generatePointsArray();
  32420. }
  32421. return false;
  32422. };
  32423. /**
  32424. * Returns a new Mesh object generated from the current mesh properties.
  32425. * This method must not get confused with createInstance().
  32426. * The parameter `name` is a string, the name given to the new mesh.
  32427. * The optional parameter `newParent` can be any Node object (default `null`).
  32428. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  32429. * 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.
  32430. */
  32431. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32432. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32433. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32434. };
  32435. /**
  32436. * Releases resources associated with this mesh.
  32437. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32438. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32439. */
  32440. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32441. var _this = this;
  32442. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32443. this.morphTargetManager = null;
  32444. if (this._geometry) {
  32445. this._geometry.releaseForMesh(this, true);
  32446. }
  32447. // Sources
  32448. var meshes = this.getScene().meshes;
  32449. meshes.forEach(function (abstractMesh) {
  32450. var mesh = abstractMesh;
  32451. if (mesh._source && mesh._source === _this) {
  32452. mesh._source = null;
  32453. }
  32454. });
  32455. this._source = null;
  32456. // Instances
  32457. if (this._instancesBuffer) {
  32458. this._instancesBuffer.dispose();
  32459. this._instancesBuffer = null;
  32460. }
  32461. while (this.instances.length) {
  32462. this.instances[0].dispose();
  32463. }
  32464. // Effect layers.
  32465. var effectLayers = this.getScene().effectLayers;
  32466. for (var i = 0; i < effectLayers.length; i++) {
  32467. var effectLayer = effectLayers[i];
  32468. if (effectLayer) {
  32469. effectLayer._disposeMesh(this);
  32470. }
  32471. }
  32472. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32473. };
  32474. /**
  32475. * Modifies the mesh geometry according to a displacement map.
  32476. * 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.
  32477. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32478. * This method returns nothing.
  32479. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  32480. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32481. * 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.
  32482. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32483. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32484. *
  32485. * Returns the Mesh.
  32486. */
  32487. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  32488. var _this = this;
  32489. var scene = this.getScene();
  32490. var onload = function (img) {
  32491. // Getting height map data
  32492. var canvas = document.createElement("canvas");
  32493. var context = canvas.getContext("2d");
  32494. var heightMapWidth = img.width;
  32495. var heightMapHeight = img.height;
  32496. canvas.width = heightMapWidth;
  32497. canvas.height = heightMapHeight;
  32498. context.drawImage(img, 0, 0);
  32499. // Create VertexData from map data
  32500. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32501. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32502. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  32503. //execute success callback, if set
  32504. if (onSuccess) {
  32505. onSuccess(_this);
  32506. }
  32507. };
  32508. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32509. return this;
  32510. };
  32511. /**
  32512. * Modifies the mesh geometry according to a displacementMap buffer.
  32513. * 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.
  32514. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32515. * This method returns nothing.
  32516. * 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.
  32517. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  32518. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32519. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32520. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32521. *
  32522. * Returns the Mesh.
  32523. */
  32524. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  32525. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32526. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32527. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32528. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32529. return this;
  32530. }
  32531. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32532. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32533. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32534. var position = BABYLON.Vector3.Zero();
  32535. var normal = BABYLON.Vector3.Zero();
  32536. var uv = BABYLON.Vector2.Zero();
  32537. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  32538. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  32539. for (var index = 0; index < positions.length; index += 3) {
  32540. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  32541. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  32542. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  32543. // Compute height
  32544. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  32545. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  32546. var pos = (u + v * heightMapWidth) * 4;
  32547. var r = buffer[pos] / 255.0;
  32548. var g = buffer[pos + 1] / 255.0;
  32549. var b = buffer[pos + 2] / 255.0;
  32550. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  32551. normal.normalize();
  32552. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  32553. position = position.add(normal);
  32554. position.toArray(positions, index);
  32555. }
  32556. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  32557. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32558. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32559. return this;
  32560. };
  32561. /**
  32562. * Modify the mesh to get a flat shading rendering.
  32563. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  32564. * This method returns the Mesh.
  32565. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  32566. */
  32567. Mesh.prototype.convertToFlatShadedMesh = function () {
  32568. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  32569. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32570. var kinds = this.getVerticesDataKinds();
  32571. var vbs = {};
  32572. var data = {};
  32573. var newdata = {};
  32574. var updatableNormals = false;
  32575. var kindIndex;
  32576. var kind;
  32577. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32578. kind = kinds[kindIndex];
  32579. var vertexBuffer = this.getVertexBuffer(kind);
  32580. if (kind === BABYLON.VertexBuffer.NormalKind) {
  32581. updatableNormals = vertexBuffer.isUpdatable();
  32582. kinds.splice(kindIndex, 1);
  32583. kindIndex--;
  32584. continue;
  32585. }
  32586. vbs[kind] = vertexBuffer;
  32587. data[kind] = vbs[kind].getData();
  32588. newdata[kind] = [];
  32589. }
  32590. // Save previous submeshes
  32591. var previousSubmeshes = this.subMeshes.slice(0);
  32592. var indices = this.getIndices();
  32593. var totalIndices = this.getTotalIndices();
  32594. // Generating unique vertices per face
  32595. var index;
  32596. for (index = 0; index < totalIndices; index++) {
  32597. var vertexIndex = indices[index];
  32598. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32599. kind = kinds[kindIndex];
  32600. var stride = vbs[kind].getStrideSize();
  32601. for (var offset = 0; offset < stride; offset++) {
  32602. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32603. }
  32604. }
  32605. }
  32606. // Updating faces & normal
  32607. var normals = [];
  32608. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  32609. for (index = 0; index < totalIndices; index += 3) {
  32610. indices[index] = index;
  32611. indices[index + 1] = index + 1;
  32612. indices[index + 2] = index + 2;
  32613. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  32614. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  32615. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  32616. var p1p2 = p1.subtract(p2);
  32617. var p3p2 = p3.subtract(p2);
  32618. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  32619. // Store same normals for every vertex
  32620. for (var localIndex = 0; localIndex < 3; localIndex++) {
  32621. normals.push(normal.x);
  32622. normals.push(normal.y);
  32623. normals.push(normal.z);
  32624. }
  32625. }
  32626. this.setIndices(indices);
  32627. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  32628. // Updating vertex buffers
  32629. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32630. kind = kinds[kindIndex];
  32631. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32632. }
  32633. // Updating submeshes
  32634. this.releaseSubMeshes();
  32635. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32636. var previousOne = previousSubmeshes[submeshIndex];
  32637. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32638. }
  32639. this.synchronizeInstances();
  32640. return this;
  32641. };
  32642. /**
  32643. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  32644. * In other words, more vertices, no more indices and a single bigger VBO.
  32645. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  32646. * Returns the Mesh.
  32647. */
  32648. Mesh.prototype.convertToUnIndexedMesh = function () {
  32649. /// <summary>Remove indices by unfolding faces into buffers</summary>
  32650. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32651. var kinds = this.getVerticesDataKinds();
  32652. var vbs = {};
  32653. var data = {};
  32654. var newdata = {};
  32655. var kindIndex;
  32656. var kind;
  32657. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32658. kind = kinds[kindIndex];
  32659. var vertexBuffer = this.getVertexBuffer(kind);
  32660. vbs[kind] = vertexBuffer;
  32661. data[kind] = vbs[kind].getData();
  32662. newdata[kind] = [];
  32663. }
  32664. // Save previous submeshes
  32665. var previousSubmeshes = this.subMeshes.slice(0);
  32666. var indices = this.getIndices();
  32667. var totalIndices = this.getTotalIndices();
  32668. // Generating unique vertices per face
  32669. var index;
  32670. for (index = 0; index < totalIndices; index++) {
  32671. var vertexIndex = indices[index];
  32672. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32673. kind = kinds[kindIndex];
  32674. var stride = vbs[kind].getStrideSize();
  32675. for (var offset = 0; offset < stride; offset++) {
  32676. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32677. }
  32678. }
  32679. }
  32680. // Updating indices
  32681. for (index = 0; index < totalIndices; index += 3) {
  32682. indices[index] = index;
  32683. indices[index + 1] = index + 1;
  32684. indices[index + 2] = index + 2;
  32685. }
  32686. this.setIndices(indices);
  32687. // Updating vertex buffers
  32688. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32689. kind = kinds[kindIndex];
  32690. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32691. }
  32692. // Updating submeshes
  32693. this.releaseSubMeshes();
  32694. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32695. var previousOne = previousSubmeshes[submeshIndex];
  32696. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32697. }
  32698. this._unIndexed = true;
  32699. this.synchronizeInstances();
  32700. return this;
  32701. };
  32702. /**
  32703. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  32704. * This method returns the Mesh.
  32705. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  32706. */
  32707. Mesh.prototype.flipFaces = function (flipNormals) {
  32708. if (flipNormals === void 0) { flipNormals = false; }
  32709. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  32710. var i;
  32711. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  32712. for (i = 0; i < vertex_data.normals.length; i++) {
  32713. vertex_data.normals[i] *= -1;
  32714. }
  32715. }
  32716. if (vertex_data.indices) {
  32717. var temp;
  32718. for (i = 0; i < vertex_data.indices.length; i += 3) {
  32719. // reassign indices
  32720. temp = vertex_data.indices[i + 1];
  32721. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  32722. vertex_data.indices[i + 2] = temp;
  32723. }
  32724. }
  32725. vertex_data.applyToMesh(this);
  32726. return this;
  32727. };
  32728. // Instances
  32729. /**
  32730. * Creates a new InstancedMesh object from the mesh model.
  32731. * An instance shares the same properties and the same material than its model.
  32732. * Only these properties of each instance can then be set individually :
  32733. * - position
  32734. * - rotation
  32735. * - rotationQuaternion
  32736. * - setPivotMatrix
  32737. * - scaling
  32738. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  32739. * Warning : this method is not supported for Line mesh and LineSystem
  32740. */
  32741. Mesh.prototype.createInstance = function (name) {
  32742. return new BABYLON.InstancedMesh(name, this);
  32743. };
  32744. /**
  32745. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  32746. * After this call, all the mesh instances have the same submeshes than the current mesh.
  32747. * This method returns the Mesh.
  32748. */
  32749. Mesh.prototype.synchronizeInstances = function () {
  32750. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  32751. var instance = this.instances[instanceIndex];
  32752. instance._syncSubMeshes();
  32753. }
  32754. return this;
  32755. };
  32756. /**
  32757. * Simplify the mesh according to the given array of settings.
  32758. * Function will return immediately and will simplify async. It returns the Mesh.
  32759. * @param settings a collection of simplification settings.
  32760. * @param parallelProcessing should all levels calculate parallel or one after the other.
  32761. * @param type the type of simplification to run.
  32762. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  32763. */
  32764. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  32765. if (parallelProcessing === void 0) { parallelProcessing = true; }
  32766. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  32767. this.getScene().simplificationQueue.addTask({
  32768. settings: settings,
  32769. parallelProcessing: parallelProcessing,
  32770. mesh: this,
  32771. simplificationType: simplificationType,
  32772. successCallback: successCallback
  32773. });
  32774. return this;
  32775. };
  32776. /**
  32777. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  32778. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  32779. * This should be used together with the simplification to avoid disappearing triangles.
  32780. * Returns the Mesh.
  32781. * @param successCallback an optional success callback to be called after the optimization finished.
  32782. */
  32783. Mesh.prototype.optimizeIndices = function (successCallback) {
  32784. var _this = this;
  32785. var indices = this.getIndices();
  32786. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32787. if (!positions || !indices) {
  32788. return this;
  32789. }
  32790. var vectorPositions = new Array();
  32791. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  32792. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  32793. }
  32794. var dupes = new Array();
  32795. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  32796. var realPos = vectorPositions.length - 1 - iteration;
  32797. var testedPosition = vectorPositions[realPos];
  32798. for (var j = 0; j < realPos; ++j) {
  32799. var againstPosition = vectorPositions[j];
  32800. if (testedPosition.equals(againstPosition)) {
  32801. dupes[realPos] = j;
  32802. break;
  32803. }
  32804. }
  32805. }, function () {
  32806. for (var i = 0; i < indices.length; ++i) {
  32807. indices[i] = dupes[indices[i]] || indices[i];
  32808. }
  32809. //indices are now reordered
  32810. var originalSubMeshes = _this.subMeshes.slice(0);
  32811. _this.setIndices(indices);
  32812. _this.subMeshes = originalSubMeshes;
  32813. if (successCallback) {
  32814. successCallback(_this);
  32815. }
  32816. });
  32817. return this;
  32818. };
  32819. Mesh.prototype.serialize = function (serializationObject) {
  32820. serializationObject.name = this.name;
  32821. serializationObject.id = this.id;
  32822. serializationObject.type = this.getClassName();
  32823. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  32824. serializationObject.tags = BABYLON.Tags.GetTags(this);
  32825. }
  32826. serializationObject.position = this.position.asArray();
  32827. if (this.rotationQuaternion) {
  32828. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  32829. }
  32830. else if (this.rotation) {
  32831. serializationObject.rotation = this.rotation.asArray();
  32832. }
  32833. serializationObject.scaling = this.scaling.asArray();
  32834. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  32835. serializationObject.isEnabled = this.isEnabled(false);
  32836. serializationObject.isVisible = this.isVisible;
  32837. serializationObject.infiniteDistance = this.infiniteDistance;
  32838. serializationObject.pickable = this.isPickable;
  32839. serializationObject.receiveShadows = this.receiveShadows;
  32840. serializationObject.billboardMode = this.billboardMode;
  32841. serializationObject.visibility = this.visibility;
  32842. serializationObject.checkCollisions = this.checkCollisions;
  32843. serializationObject.isBlocker = this.isBlocker;
  32844. // Parent
  32845. if (this.parent) {
  32846. serializationObject.parentId = this.parent.id;
  32847. }
  32848. // Geometry
  32849. serializationObject.isUnIndexed = this.isUnIndexed;
  32850. var geometry = this._geometry;
  32851. if (geometry) {
  32852. var geometryId = geometry.id;
  32853. serializationObject.geometryId = geometryId;
  32854. // SubMeshes
  32855. serializationObject.subMeshes = [];
  32856. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  32857. var subMesh = this.subMeshes[subIndex];
  32858. serializationObject.subMeshes.push({
  32859. materialIndex: subMesh.materialIndex,
  32860. verticesStart: subMesh.verticesStart,
  32861. verticesCount: subMesh.verticesCount,
  32862. indexStart: subMesh.indexStart,
  32863. indexCount: subMesh.indexCount
  32864. });
  32865. }
  32866. }
  32867. // Material
  32868. if (this.material) {
  32869. serializationObject.materialId = this.material.id;
  32870. }
  32871. else {
  32872. this.material = null;
  32873. }
  32874. // Morph targets
  32875. if (this.morphTargetManager) {
  32876. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  32877. }
  32878. // Skeleton
  32879. if (this.skeleton) {
  32880. serializationObject.skeletonId = this.skeleton.id;
  32881. }
  32882. // Physics
  32883. //TODO implement correct serialization for physics impostors.
  32884. var impostor = this.getPhysicsImpostor();
  32885. if (impostor) {
  32886. serializationObject.physicsMass = impostor.getParam("mass");
  32887. serializationObject.physicsFriction = impostor.getParam("friction");
  32888. serializationObject.physicsRestitution = impostor.getParam("mass");
  32889. serializationObject.physicsImpostor = impostor.type;
  32890. }
  32891. // Metadata
  32892. if (this.metadata) {
  32893. serializationObject.metadata = this.metadata;
  32894. }
  32895. // Instances
  32896. serializationObject.instances = [];
  32897. for (var index = 0; index < this.instances.length; index++) {
  32898. var instance = this.instances[index];
  32899. var serializationInstance = {
  32900. name: instance.name,
  32901. id: instance.id,
  32902. position: instance.position.asArray(),
  32903. scaling: instance.scaling.asArray()
  32904. };
  32905. if (instance.rotationQuaternion) {
  32906. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  32907. }
  32908. else if (instance.rotation) {
  32909. serializationInstance.rotation = instance.rotation.asArray();
  32910. }
  32911. serializationObject.instances.push(serializationInstance);
  32912. // Animations
  32913. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  32914. serializationInstance.ranges = instance.serializeAnimationRanges();
  32915. }
  32916. //
  32917. // Animations
  32918. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  32919. serializationObject.ranges = this.serializeAnimationRanges();
  32920. // Layer mask
  32921. serializationObject.layerMask = this.layerMask;
  32922. // Alpha
  32923. serializationObject.alphaIndex = this.alphaIndex;
  32924. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  32925. // Overlay
  32926. serializationObject.overlayAlpha = this.overlayAlpha;
  32927. serializationObject.overlayColor = this.overlayColor.asArray();
  32928. serializationObject.renderOverlay = this.renderOverlay;
  32929. // Fog
  32930. serializationObject.applyFog = this.applyFog;
  32931. // Action Manager
  32932. if (this.actionManager) {
  32933. serializationObject.actions = this.actionManager.serialize(this.name);
  32934. }
  32935. };
  32936. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  32937. if (!this.geometry) {
  32938. return;
  32939. }
  32940. this._markSubMeshesAsAttributesDirty();
  32941. var morphTargetManager = this._morphTargetManager;
  32942. if (morphTargetManager && morphTargetManager.vertexCount) {
  32943. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  32944. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  32945. this.morphTargetManager = null;
  32946. return;
  32947. }
  32948. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  32949. var morphTarget = morphTargetManager.getActiveTarget(index);
  32950. var positions = morphTarget.getPositions();
  32951. if (!positions) {
  32952. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  32953. return;
  32954. }
  32955. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  32956. var normals = morphTarget.getNormals();
  32957. if (normals) {
  32958. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  32959. }
  32960. var tangents = morphTarget.getTangents();
  32961. if (tangents) {
  32962. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  32963. }
  32964. }
  32965. }
  32966. else {
  32967. var index = 0;
  32968. // Positions
  32969. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  32970. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  32971. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  32972. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  32973. }
  32974. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  32975. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  32976. }
  32977. index++;
  32978. }
  32979. }
  32980. };
  32981. // Statics
  32982. /**
  32983. * Returns a new Mesh object parsed from the source provided.
  32984. * The parameter `parsedMesh` is the source.
  32985. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  32986. */
  32987. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  32988. var mesh;
  32989. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  32990. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  32991. }
  32992. else {
  32993. mesh = new Mesh(parsedMesh.name, scene);
  32994. }
  32995. mesh.id = parsedMesh.id;
  32996. if (BABYLON.Tags) {
  32997. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  32998. }
  32999. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  33000. if (parsedMesh.metadata !== undefined) {
  33001. mesh.metadata = parsedMesh.metadata;
  33002. }
  33003. if (parsedMesh.rotationQuaternion) {
  33004. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  33005. }
  33006. else if (parsedMesh.rotation) {
  33007. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  33008. }
  33009. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  33010. if (parsedMesh.localMatrix) {
  33011. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  33012. }
  33013. else if (parsedMesh.pivotMatrix) {
  33014. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  33015. }
  33016. mesh.setEnabled(parsedMesh.isEnabled);
  33017. mesh.isVisible = parsedMesh.isVisible;
  33018. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  33019. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  33020. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  33021. if (parsedMesh.applyFog !== undefined) {
  33022. mesh.applyFog = parsedMesh.applyFog;
  33023. }
  33024. if (parsedMesh.pickable !== undefined) {
  33025. mesh.isPickable = parsedMesh.pickable;
  33026. }
  33027. if (parsedMesh.alphaIndex !== undefined) {
  33028. mesh.alphaIndex = parsedMesh.alphaIndex;
  33029. }
  33030. mesh.receiveShadows = parsedMesh.receiveShadows;
  33031. mesh.billboardMode = parsedMesh.billboardMode;
  33032. if (parsedMesh.visibility !== undefined) {
  33033. mesh.visibility = parsedMesh.visibility;
  33034. }
  33035. mesh.checkCollisions = parsedMesh.checkCollisions;
  33036. if (parsedMesh.isBlocker !== undefined) {
  33037. mesh.isBlocker = parsedMesh.isBlocker;
  33038. }
  33039. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  33040. // freezeWorldMatrix
  33041. if (parsedMesh.freezeWorldMatrix) {
  33042. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  33043. }
  33044. // Parent
  33045. if (parsedMesh.parentId) {
  33046. mesh._waitingParentId = parsedMesh.parentId;
  33047. }
  33048. // Actions
  33049. if (parsedMesh.actions !== undefined) {
  33050. mesh._waitingActions = parsedMesh.actions;
  33051. }
  33052. // Overlay
  33053. if (parsedMesh.overlayAlpha !== undefined) {
  33054. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  33055. }
  33056. if (parsedMesh.overlayColor !== undefined) {
  33057. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  33058. }
  33059. if (parsedMesh.renderOverlay !== undefined) {
  33060. mesh.renderOverlay = parsedMesh.renderOverlay;
  33061. }
  33062. // Geometry
  33063. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  33064. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  33065. if (parsedMesh.delayLoadingFile) {
  33066. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33067. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  33068. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  33069. if (parsedMesh._binaryInfo) {
  33070. mesh._binaryInfo = parsedMesh._binaryInfo;
  33071. }
  33072. mesh._delayInfo = [];
  33073. if (parsedMesh.hasUVs) {
  33074. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33075. }
  33076. if (parsedMesh.hasUVs2) {
  33077. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33078. }
  33079. if (parsedMesh.hasUVs3) {
  33080. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33081. }
  33082. if (parsedMesh.hasUVs4) {
  33083. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33084. }
  33085. if (parsedMesh.hasUVs5) {
  33086. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33087. }
  33088. if (parsedMesh.hasUVs6) {
  33089. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33090. }
  33091. if (parsedMesh.hasColors) {
  33092. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33093. }
  33094. if (parsedMesh.hasMatricesIndices) {
  33095. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33096. }
  33097. if (parsedMesh.hasMatricesWeights) {
  33098. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33099. }
  33100. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33101. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33102. mesh._checkDelayState();
  33103. }
  33104. }
  33105. else {
  33106. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33107. }
  33108. // Material
  33109. if (parsedMesh.materialId) {
  33110. mesh.setMaterialByID(parsedMesh.materialId);
  33111. }
  33112. else {
  33113. mesh.material = null;
  33114. }
  33115. // Morph targets
  33116. if (parsedMesh.morphTargetManagerId > -1) {
  33117. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33118. }
  33119. // Skeleton
  33120. if (parsedMesh.skeletonId > -1) {
  33121. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33122. if (parsedMesh.numBoneInfluencers) {
  33123. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33124. }
  33125. }
  33126. // Animations
  33127. if (parsedMesh.animations) {
  33128. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33129. var parsedAnimation = parsedMesh.animations[animationIndex];
  33130. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33131. }
  33132. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33133. }
  33134. if (parsedMesh.autoAnimate) {
  33135. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33136. }
  33137. // Layer Mask
  33138. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33139. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33140. }
  33141. else {
  33142. mesh.layerMask = 0x0FFFFFFF;
  33143. }
  33144. // Physics
  33145. if (parsedMesh.physicsImpostor) {
  33146. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33147. mass: parsedMesh.physicsMass,
  33148. friction: parsedMesh.physicsFriction,
  33149. restitution: parsedMesh.physicsRestitution
  33150. }, scene);
  33151. }
  33152. // Instances
  33153. if (parsedMesh.instances) {
  33154. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33155. var parsedInstance = parsedMesh.instances[index];
  33156. var instance = mesh.createInstance(parsedInstance.name);
  33157. if (parsedInstance.id) {
  33158. instance.id = parsedInstance.id;
  33159. }
  33160. if (BABYLON.Tags) {
  33161. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33162. }
  33163. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33164. if (parsedInstance.parentId) {
  33165. instance._waitingParentId = parsedInstance.parentId;
  33166. }
  33167. if (parsedInstance.rotationQuaternion) {
  33168. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33169. }
  33170. else if (parsedInstance.rotation) {
  33171. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33172. }
  33173. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33174. instance.checkCollisions = mesh.checkCollisions;
  33175. if (parsedMesh.animations) {
  33176. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33177. parsedAnimation = parsedMesh.animations[animationIndex];
  33178. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33179. }
  33180. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  33181. }
  33182. }
  33183. }
  33184. return mesh;
  33185. };
  33186. /**
  33187. * Creates a ribbon mesh.
  33188. * Please consider using the same method from the MeshBuilder class instead.
  33189. * 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.
  33190. *
  33191. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  33192. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33193. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  33194. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  33195. * 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.
  33196. * 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.
  33197. * 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
  33198. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33199. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33200. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33201. */
  33202. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33203. if (closeArray === void 0) { closeArray = false; }
  33204. if (updatable === void 0) { updatable = false; }
  33205. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33206. pathArray: pathArray,
  33207. closeArray: closeArray,
  33208. closePath: closePath,
  33209. offset: offset,
  33210. updatable: updatable,
  33211. sideOrientation: sideOrientation,
  33212. instance: instance
  33213. }, scene);
  33214. };
  33215. /**
  33216. * Creates a plane polygonal mesh. By default, this is a disc.
  33217. * Please consider using the same method from the MeshBuilder class instead.
  33218. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  33219. * 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.
  33220. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33221. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33222. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33223. */
  33224. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33225. if (scene === void 0) { scene = null; }
  33226. var options = {
  33227. radius: radius,
  33228. tessellation: tessellation,
  33229. sideOrientation: sideOrientation,
  33230. updatable: updatable
  33231. };
  33232. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33233. };
  33234. /**
  33235. * Creates a box mesh.
  33236. * Please consider using the same method from the MeshBuilder class instead.
  33237. * The parameter `size` sets the size (float) of each box side (default 1).
  33238. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33239. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33240. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33241. */
  33242. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33243. if (scene === void 0) { scene = null; }
  33244. var options = {
  33245. size: size,
  33246. sideOrientation: sideOrientation,
  33247. updatable: updatable
  33248. };
  33249. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33250. };
  33251. /**
  33252. * Creates a sphere mesh.
  33253. * Please consider using the same method from the MeshBuilder class instead.
  33254. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  33255. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  33256. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33257. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33258. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33259. */
  33260. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33261. var options = {
  33262. segments: segments,
  33263. diameterX: diameter,
  33264. diameterY: diameter,
  33265. diameterZ: diameter,
  33266. sideOrientation: sideOrientation,
  33267. updatable: updatable
  33268. };
  33269. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33270. };
  33271. /**
  33272. * Creates a cylinder or a cone mesh.
  33273. * Please consider using the same method from the MeshBuilder class instead.
  33274. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  33275. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  33276. * 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.
  33277. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  33278. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  33279. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33280. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33281. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33282. */
  33283. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33284. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33285. if (scene !== undefined) {
  33286. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33287. updatable = scene;
  33288. }
  33289. scene = subdivisions;
  33290. subdivisions = 1;
  33291. }
  33292. var options = {
  33293. height: height,
  33294. diameterTop: diameterTop,
  33295. diameterBottom: diameterBottom,
  33296. tessellation: tessellation,
  33297. subdivisions: subdivisions,
  33298. sideOrientation: sideOrientation,
  33299. updatable: updatable
  33300. };
  33301. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33302. };
  33303. // Torus (Code from SharpDX.org)
  33304. /**
  33305. * Creates a torus mesh.
  33306. * Please consider using the same method from the MeshBuilder class instead.
  33307. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  33308. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  33309. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  33310. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33311. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33312. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33313. */
  33314. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33315. var options = {
  33316. diameter: diameter,
  33317. thickness: thickness,
  33318. tessellation: tessellation,
  33319. sideOrientation: sideOrientation,
  33320. updatable: updatable
  33321. };
  33322. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33323. };
  33324. /**
  33325. * Creates a torus knot mesh.
  33326. * Please consider using the same method from the MeshBuilder class instead.
  33327. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  33328. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  33329. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  33330. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  33331. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33332. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33333. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33334. */
  33335. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33336. var options = {
  33337. radius: radius,
  33338. tube: tube,
  33339. radialSegments: radialSegments,
  33340. tubularSegments: tubularSegments,
  33341. p: p,
  33342. q: q,
  33343. sideOrientation: sideOrientation,
  33344. updatable: updatable
  33345. };
  33346. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33347. };
  33348. /**
  33349. * Creates a line mesh.
  33350. * Please consider using the same method from the MeshBuilder class instead.
  33351. * 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.
  33352. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33353. * The parameter `points` is an array successive Vector3.
  33354. * 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
  33355. * When updating an instance, remember that only point positions can change, not the number of points.
  33356. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33357. */
  33358. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33359. if (scene === void 0) { scene = null; }
  33360. if (updatable === void 0) { updatable = false; }
  33361. if (instance === void 0) { instance = null; }
  33362. var options = {
  33363. points: points,
  33364. updatable: updatable,
  33365. instance: instance
  33366. };
  33367. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33368. };
  33369. /**
  33370. * Creates a dashed line mesh.
  33371. * Please consider using the same method from the MeshBuilder class instead.
  33372. * 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.
  33373. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33374. * The parameter `points` is an array successive Vector3.
  33375. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  33376. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  33377. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  33378. * 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
  33379. * When updating an instance, remember that only point positions can change, not the number of points.
  33380. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33381. */
  33382. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33383. if (scene === void 0) { scene = null; }
  33384. var options = {
  33385. points: points,
  33386. dashSize: dashSize,
  33387. gapSize: gapSize,
  33388. dashNb: dashNb,
  33389. updatable: updatable,
  33390. instance: instance
  33391. };
  33392. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33393. };
  33394. /**
  33395. * Creates a polygon mesh.
  33396. * Please consider using the same method from the MeshBuilder class instead.
  33397. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33398. * 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.
  33399. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33400. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33401. * Remember you can only change the shape positions, not their number when updating a polygon.
  33402. */
  33403. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33404. var options = {
  33405. shape: shape,
  33406. holes: holes,
  33407. updatable: updatable,
  33408. sideOrientation: sideOrientation
  33409. };
  33410. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33411. };
  33412. /**
  33413. * Creates an extruded polygon mesh, with depth in the Y direction.
  33414. * Please consider using the same method from the MeshBuilder class instead.
  33415. */
  33416. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33417. var options = {
  33418. shape: shape,
  33419. holes: holes,
  33420. depth: depth,
  33421. updatable: updatable,
  33422. sideOrientation: sideOrientation
  33423. };
  33424. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33425. };
  33426. /**
  33427. * Creates an extruded shape mesh.
  33428. * 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.
  33429. * Please consider using the same method from the MeshBuilder class instead.
  33430. *
  33431. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33432. * 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
  33433. * extruded along the Z axis.
  33434. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33435. * 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.
  33436. * The parameter `scale` (float, default 1) is the value to scale the shape.
  33437. * 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
  33438. * 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
  33439. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33440. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33441. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33442. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33443. */
  33444. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33445. if (scene === void 0) { scene = null; }
  33446. var options = {
  33447. shape: shape,
  33448. path: path,
  33449. scale: scale,
  33450. rotation: rotation,
  33451. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33452. sideOrientation: sideOrientation,
  33453. instance: instance,
  33454. updatable: updatable
  33455. };
  33456. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33457. };
  33458. /**
  33459. * Creates an custom extruded shape mesh.
  33460. * 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.
  33461. * Please consider using the same method from the MeshBuilder class instead.
  33462. *
  33463. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33464. * 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
  33465. * extruded along the Z axis.
  33466. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33467. * 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
  33468. * and the distance of this point from the begining of the path :
  33469. * ```javascript
  33470. * var rotationFunction = function(i, distance) {
  33471. * // do things
  33472. * return rotationValue; }
  33473. * ```
  33474. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  33475. * 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
  33476. * and the distance of this point from the begining of the path :
  33477. * ```javascript
  33478. * var scaleFunction = function(i, distance) {
  33479. * // do things
  33480. * return scaleValue;}
  33481. * ```
  33482. * It must returns a float value that will be the scale value applied to the shape on each path point.
  33483. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  33484. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  33485. * 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
  33486. * 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
  33487. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33488. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33489. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33490. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33491. */
  33492. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33493. var options = {
  33494. shape: shape,
  33495. path: path,
  33496. scaleFunction: scaleFunction,
  33497. rotationFunction: rotationFunction,
  33498. ribbonCloseArray: ribbonCloseArray,
  33499. ribbonClosePath: ribbonClosePath,
  33500. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33501. sideOrientation: sideOrientation,
  33502. instance: instance,
  33503. updatable: updatable
  33504. };
  33505. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33506. };
  33507. /**
  33508. * Creates lathe mesh.
  33509. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33510. * Please consider using the same method from the MeshBuilder class instead.
  33511. * 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
  33512. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  33513. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  33514. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  33515. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33516. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33517. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33518. */
  33519. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33520. var options = {
  33521. shape: shape,
  33522. radius: radius,
  33523. tessellation: tessellation,
  33524. sideOrientation: sideOrientation,
  33525. updatable: updatable
  33526. };
  33527. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33528. };
  33529. /**
  33530. * Creates a plane mesh.
  33531. * Please consider using the same method from the MeshBuilder class instead.
  33532. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  33533. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33534. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33535. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33536. */
  33537. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  33538. var options = {
  33539. size: size,
  33540. width: size,
  33541. height: size,
  33542. sideOrientation: sideOrientation,
  33543. updatable: updatable
  33544. };
  33545. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  33546. };
  33547. /**
  33548. * Creates a ground mesh.
  33549. * Please consider using the same method from the MeshBuilder class instead.
  33550. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  33551. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  33552. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33553. */
  33554. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  33555. var options = {
  33556. width: width,
  33557. height: height,
  33558. subdivisions: subdivisions,
  33559. updatable: updatable
  33560. };
  33561. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  33562. };
  33563. /**
  33564. * Creates a tiled ground mesh.
  33565. * Please consider using the same method from the MeshBuilder class instead.
  33566. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  33567. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  33568. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  33569. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  33570. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  33571. * numbers of subdivisions on the ground width and height of each tile.
  33572. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33573. */
  33574. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  33575. var options = {
  33576. xmin: xmin,
  33577. zmin: zmin,
  33578. xmax: xmax,
  33579. zmax: zmax,
  33580. subdivisions: subdivisions,
  33581. precision: precision,
  33582. updatable: updatable
  33583. };
  33584. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  33585. };
  33586. /**
  33587. * Creates a ground mesh from a height map.
  33588. * tuto : http://doc.babylonjs.com/babylon101/height_map
  33589. * Please consider using the same method from the MeshBuilder class instead.
  33590. * The parameter `url` sets the URL of the height map image resource.
  33591. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  33592. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  33593. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  33594. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  33595. * 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).
  33596. * This function is passed the newly built mesh :
  33597. * ```javascript
  33598. * function(mesh) { // do things
  33599. * return; }
  33600. * ```
  33601. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33602. */
  33603. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  33604. var options = {
  33605. width: width,
  33606. height: height,
  33607. subdivisions: subdivisions,
  33608. minHeight: minHeight,
  33609. maxHeight: maxHeight,
  33610. updatable: updatable,
  33611. onReady: onReady
  33612. };
  33613. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  33614. };
  33615. /**
  33616. * Creates a tube mesh.
  33617. * 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.
  33618. * Please consider using the same method from the MeshBuilder class instead.
  33619. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  33620. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  33621. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  33622. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  33623. * 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.
  33624. * It must return a radius value (positive float) :
  33625. * ```javascript
  33626. * var radiusFunction = function(i, distance) {
  33627. * // do things
  33628. * return radius; }
  33629. * ```
  33630. * 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
  33631. * 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
  33632. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33633. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33634. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33635. */
  33636. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  33637. var options = {
  33638. path: path,
  33639. radius: radius,
  33640. tessellation: tessellation,
  33641. radiusFunction: radiusFunction,
  33642. arc: 1,
  33643. cap: cap,
  33644. updatable: updatable,
  33645. sideOrientation: sideOrientation,
  33646. instance: instance
  33647. };
  33648. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  33649. };
  33650. /**
  33651. * Creates a polyhedron mesh.
  33652. * Please consider using the same method from the MeshBuilder class instead.
  33653. * 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
  33654. * to choose the wanted type.
  33655. * The parameter `size` (positive float, default 1) sets the polygon size.
  33656. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  33657. * 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`.
  33658. * 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
  33659. * 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)`).
  33660. * 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
  33661. * 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.
  33662. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33663. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33664. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33665. */
  33666. Mesh.CreatePolyhedron = function (name, options, scene) {
  33667. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  33668. };
  33669. /**
  33670. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  33671. * Please consider using the same method from the MeshBuilder class instead.
  33672. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  33673. * 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`).
  33674. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  33675. * 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.
  33676. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33677. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33678. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33679. */
  33680. Mesh.CreateIcoSphere = function (name, options, scene) {
  33681. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  33682. };
  33683. /**
  33684. * Creates a decal mesh.
  33685. * Please consider using the same method from the MeshBuilder class instead.
  33686. * 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.
  33687. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  33688. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  33689. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  33690. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  33691. */
  33692. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  33693. var options = {
  33694. position: position,
  33695. normal: normal,
  33696. size: size,
  33697. angle: angle
  33698. };
  33699. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  33700. };
  33701. // Skeletons
  33702. /**
  33703. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33704. */
  33705. Mesh.prototype.setPositionsForCPUSkinning = function () {
  33706. if (!this._sourcePositions) {
  33707. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33708. if (!source) {
  33709. return this._sourcePositions;
  33710. }
  33711. this._sourcePositions = new Float32Array(source);
  33712. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  33713. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  33714. }
  33715. }
  33716. return this._sourcePositions;
  33717. };
  33718. /**
  33719. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33720. */
  33721. Mesh.prototype.setNormalsForCPUSkinning = function () {
  33722. if (!this._sourceNormals) {
  33723. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33724. if (!source) {
  33725. return this._sourceNormals;
  33726. }
  33727. this._sourceNormals = new Float32Array(source);
  33728. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  33729. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  33730. }
  33731. }
  33732. return this._sourceNormals;
  33733. };
  33734. /**
  33735. * Updates the vertex buffer by applying transformation from the bones.
  33736. * Returns the Mesh.
  33737. *
  33738. * @param {skeleton} skeleton to apply
  33739. */
  33740. Mesh.prototype.applySkeleton = function (skeleton) {
  33741. if (!this.geometry) {
  33742. return this;
  33743. }
  33744. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  33745. return this;
  33746. }
  33747. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  33748. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33749. return this;
  33750. }
  33751. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33752. return this;
  33753. }
  33754. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33755. return this;
  33756. }
  33757. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33758. return this;
  33759. }
  33760. if (!this._sourcePositions) {
  33761. var submeshes = this.subMeshes.slice();
  33762. this.setPositionsForCPUSkinning();
  33763. this.subMeshes = submeshes;
  33764. }
  33765. if (!this._sourceNormals) {
  33766. this.setNormalsForCPUSkinning();
  33767. }
  33768. // positionsData checks for not being Float32Array will only pass at most once
  33769. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33770. if (!positionsData) {
  33771. return this;
  33772. }
  33773. if (!(positionsData instanceof Float32Array)) {
  33774. positionsData = new Float32Array(positionsData);
  33775. }
  33776. // normalsData checks for not being Float32Array will only pass at most once
  33777. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33778. if (!normalsData) {
  33779. return this;
  33780. }
  33781. if (!(normalsData instanceof Float32Array)) {
  33782. normalsData = new Float32Array(normalsData);
  33783. }
  33784. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33785. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33786. if (!matricesWeightsData || !matricesIndicesData) {
  33787. return this;
  33788. }
  33789. var needExtras = this.numBoneInfluencers > 4;
  33790. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  33791. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  33792. var skeletonMatrices = skeleton.getTransformMatrices(this);
  33793. var tempVector3 = BABYLON.Vector3.Zero();
  33794. var finalMatrix = new BABYLON.Matrix();
  33795. var tempMatrix = new BABYLON.Matrix();
  33796. var matWeightIdx = 0;
  33797. var inf;
  33798. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  33799. var weight;
  33800. for (inf = 0; inf < 4; inf++) {
  33801. weight = matricesWeightsData[matWeightIdx + inf];
  33802. if (weight > 0) {
  33803. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33804. finalMatrix.addToSelf(tempMatrix);
  33805. }
  33806. else
  33807. break;
  33808. }
  33809. if (needExtras) {
  33810. for (inf = 0; inf < 4; inf++) {
  33811. weight = matricesWeightsExtraData[matWeightIdx + inf];
  33812. if (weight > 0) {
  33813. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33814. finalMatrix.addToSelf(tempMatrix);
  33815. }
  33816. else
  33817. break;
  33818. }
  33819. }
  33820. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  33821. tempVector3.toArray(positionsData, index);
  33822. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  33823. tempVector3.toArray(normalsData, index);
  33824. finalMatrix.reset();
  33825. }
  33826. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  33827. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  33828. return this;
  33829. };
  33830. // Tools
  33831. /**
  33832. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  33833. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  33834. */
  33835. Mesh.MinMax = function (meshes) {
  33836. var minVector = null;
  33837. var maxVector = null;
  33838. meshes.forEach(function (mesh, index, array) {
  33839. var boundingInfo = mesh.getBoundingInfo();
  33840. var boundingBox = boundingInfo.boundingBox;
  33841. if (!minVector || !maxVector) {
  33842. minVector = boundingBox.minimumWorld;
  33843. maxVector = boundingBox.maximumWorld;
  33844. }
  33845. else {
  33846. minVector.minimizeInPlace(boundingBox.minimumWorld);
  33847. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  33848. }
  33849. });
  33850. if (!minVector || !maxVector) {
  33851. return {
  33852. min: BABYLON.Vector3.Zero(),
  33853. max: BABYLON.Vector3.Zero()
  33854. };
  33855. }
  33856. return {
  33857. min: minVector,
  33858. max: maxVector
  33859. };
  33860. };
  33861. /**
  33862. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  33863. */
  33864. Mesh.Center = function (meshesOrMinMaxVector) {
  33865. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  33866. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  33867. };
  33868. /**
  33869. * Merge the array of meshes into a single mesh for performance reasons.
  33870. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  33871. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  33872. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  33873. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  33874. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  33875. */
  33876. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  33877. if (disposeSource === void 0) { disposeSource = true; }
  33878. var index;
  33879. if (!allow32BitsIndices) {
  33880. var totalVertices = 0;
  33881. // Counting vertices
  33882. for (index = 0; index < meshes.length; index++) {
  33883. if (meshes[index]) {
  33884. totalVertices += meshes[index].getTotalVertices();
  33885. if (totalVertices > 65536) {
  33886. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  33887. return null;
  33888. }
  33889. }
  33890. }
  33891. }
  33892. // Merge
  33893. var vertexData = null;
  33894. var otherVertexData;
  33895. var indiceArray = new Array();
  33896. var source = null;
  33897. for (index = 0; index < meshes.length; index++) {
  33898. if (meshes[index]) {
  33899. meshes[index].computeWorldMatrix(true);
  33900. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  33901. otherVertexData.transform(meshes[index].getWorldMatrix());
  33902. if (vertexData) {
  33903. vertexData.merge(otherVertexData);
  33904. }
  33905. else {
  33906. vertexData = otherVertexData;
  33907. source = meshes[index];
  33908. }
  33909. if (subdivideWithSubMeshes) {
  33910. indiceArray.push(meshes[index].getTotalIndices());
  33911. }
  33912. }
  33913. }
  33914. source = source;
  33915. if (!meshSubclass) {
  33916. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  33917. }
  33918. vertexData.applyToMesh(meshSubclass);
  33919. // Setting properties
  33920. meshSubclass.material = source.material;
  33921. meshSubclass.checkCollisions = source.checkCollisions;
  33922. // Cleaning
  33923. if (disposeSource) {
  33924. for (index = 0; index < meshes.length; index++) {
  33925. if (meshes[index]) {
  33926. meshes[index].dispose();
  33927. }
  33928. }
  33929. }
  33930. // Subdivide
  33931. if (subdivideWithSubMeshes) {
  33932. //-- Suppresions du submesh global
  33933. meshSubclass.releaseSubMeshes();
  33934. index = 0;
  33935. var offset = 0;
  33936. //-- aplique la subdivision en fonction du tableau d'indices
  33937. while (index < indiceArray.length) {
  33938. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  33939. offset += indiceArray[index];
  33940. index++;
  33941. }
  33942. }
  33943. return meshSubclass;
  33944. };
  33945. // Consts
  33946. Mesh._FRONTSIDE = 0;
  33947. Mesh._BACKSIDE = 1;
  33948. Mesh._DOUBLESIDE = 2;
  33949. Mesh._DEFAULTSIDE = 0;
  33950. Mesh._NO_CAP = 0;
  33951. Mesh._CAP_START = 1;
  33952. Mesh._CAP_END = 2;
  33953. Mesh._CAP_ALL = 3;
  33954. return Mesh;
  33955. }(BABYLON.AbstractMesh));
  33956. BABYLON.Mesh = Mesh;
  33957. })(BABYLON || (BABYLON = {}));
  33958. //# sourceMappingURL=babylon.mesh.js.map
  33959. var BABYLON;
  33960. (function (BABYLON) {
  33961. var BaseSubMesh = /** @class */ (function () {
  33962. function BaseSubMesh() {
  33963. }
  33964. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  33965. get: function () {
  33966. return this._materialEffect;
  33967. },
  33968. enumerable: true,
  33969. configurable: true
  33970. });
  33971. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  33972. if (defines === void 0) { defines = null; }
  33973. if (this._materialEffect === effect) {
  33974. if (!effect) {
  33975. this._materialDefines = null;
  33976. }
  33977. return;
  33978. }
  33979. this._materialDefines = defines;
  33980. this._materialEffect = effect;
  33981. };
  33982. return BaseSubMesh;
  33983. }());
  33984. BABYLON.BaseSubMesh = BaseSubMesh;
  33985. var SubMesh = /** @class */ (function (_super) {
  33986. __extends(SubMesh, _super);
  33987. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  33988. if (createBoundingBox === void 0) { createBoundingBox = true; }
  33989. var _this = _super.call(this) || this;
  33990. _this.materialIndex = materialIndex;
  33991. _this.verticesStart = verticesStart;
  33992. _this.verticesCount = verticesCount;
  33993. _this.indexStart = indexStart;
  33994. _this.indexCount = indexCount;
  33995. _this._renderId = 0;
  33996. _this._mesh = mesh;
  33997. _this._renderingMesh = renderingMesh || mesh;
  33998. mesh.subMeshes.push(_this);
  33999. _this._trianglePlanes = [];
  34000. _this._id = mesh.subMeshes.length - 1;
  34001. if (createBoundingBox) {
  34002. _this.refreshBoundingInfo();
  34003. mesh.computeWorldMatrix(true);
  34004. }
  34005. return _this;
  34006. }
  34007. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34008. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34009. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  34010. };
  34011. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  34012. get: function () {
  34013. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  34014. },
  34015. enumerable: true,
  34016. configurable: true
  34017. });
  34018. /**
  34019. * Returns the submesh BoudingInfo object.
  34020. */
  34021. SubMesh.prototype.getBoundingInfo = function () {
  34022. if (this.IsGlobal) {
  34023. return this._mesh.getBoundingInfo();
  34024. }
  34025. return this._boundingInfo;
  34026. };
  34027. /**
  34028. * Sets the submesh BoundingInfo.
  34029. * Return the SubMesh.
  34030. */
  34031. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  34032. this._boundingInfo = boundingInfo;
  34033. return this;
  34034. };
  34035. /**
  34036. * Returns the mesh of the current submesh.
  34037. */
  34038. SubMesh.prototype.getMesh = function () {
  34039. return this._mesh;
  34040. };
  34041. /**
  34042. * Returns the rendering mesh of the submesh.
  34043. */
  34044. SubMesh.prototype.getRenderingMesh = function () {
  34045. return this._renderingMesh;
  34046. };
  34047. /**
  34048. * Returns the submesh material.
  34049. */
  34050. SubMesh.prototype.getMaterial = function () {
  34051. var rootMaterial = this._renderingMesh.material;
  34052. if (rootMaterial === null || rootMaterial === undefined) {
  34053. return this._mesh.getScene().defaultMaterial;
  34054. }
  34055. else if (rootMaterial.getSubMaterial) {
  34056. var multiMaterial = rootMaterial;
  34057. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  34058. if (this._currentMaterial !== effectiveMaterial) {
  34059. this._currentMaterial = effectiveMaterial;
  34060. this._materialDefines = null;
  34061. }
  34062. return effectiveMaterial;
  34063. }
  34064. return rootMaterial;
  34065. };
  34066. // Methods
  34067. /**
  34068. * Sets a new updated BoundingInfo object to the submesh.
  34069. * Returns the SubMesh.
  34070. */
  34071. SubMesh.prototype.refreshBoundingInfo = function () {
  34072. this._lastColliderWorldVertices = null;
  34073. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  34074. return this;
  34075. }
  34076. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34077. if (!data) {
  34078. this._boundingInfo = this._mesh.getBoundingInfo();
  34079. return this;
  34080. }
  34081. var indices = this._renderingMesh.getIndices();
  34082. var extend;
  34083. //is this the only submesh?
  34084. if (this.indexStart === 0 && this.indexCount === indices.length) {
  34085. var boundingInfo = this._renderingMesh.getBoundingInfo();
  34086. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  34087. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  34088. }
  34089. else {
  34090. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  34091. }
  34092. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  34093. return this;
  34094. };
  34095. SubMesh.prototype._checkCollision = function (collider) {
  34096. var boundingInfo = this.getBoundingInfo();
  34097. return boundingInfo._checkCollision(collider);
  34098. };
  34099. /**
  34100. * Updates the submesh BoundingInfo.
  34101. * Returns the Submesh.
  34102. */
  34103. SubMesh.prototype.updateBoundingInfo = function (world) {
  34104. var boundingInfo = this.getBoundingInfo();
  34105. if (!boundingInfo) {
  34106. this.refreshBoundingInfo();
  34107. boundingInfo = this.getBoundingInfo();
  34108. }
  34109. boundingInfo.update(world);
  34110. return this;
  34111. };
  34112. /**
  34113. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  34114. * Boolean returned.
  34115. */
  34116. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  34117. var boundingInfo = this.getBoundingInfo();
  34118. if (!boundingInfo) {
  34119. return false;
  34120. }
  34121. return boundingInfo.isInFrustum(frustumPlanes);
  34122. };
  34123. /**
  34124. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  34125. * Boolean returned.
  34126. */
  34127. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34128. var boundingInfo = this.getBoundingInfo();
  34129. if (!boundingInfo) {
  34130. return false;
  34131. }
  34132. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34133. };
  34134. /**
  34135. * Renders the submesh.
  34136. * Returns it.
  34137. */
  34138. SubMesh.prototype.render = function (enableAlphaMode) {
  34139. this._renderingMesh.render(this, enableAlphaMode);
  34140. return this;
  34141. };
  34142. /**
  34143. * Returns a new Index Buffer.
  34144. * Type returned : WebGLBuffer.
  34145. */
  34146. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  34147. if (!this._linesIndexBuffer) {
  34148. var linesIndices = [];
  34149. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34150. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34151. }
  34152. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34153. this.linesIndexCount = linesIndices.length;
  34154. }
  34155. return this._linesIndexBuffer;
  34156. };
  34157. /**
  34158. * True is the passed Ray intersects the submesh bounding box.
  34159. * Boolean returned.
  34160. */
  34161. SubMesh.prototype.canIntersects = function (ray) {
  34162. var boundingInfo = this.getBoundingInfo();
  34163. if (!boundingInfo) {
  34164. return false;
  34165. }
  34166. return ray.intersectsBox(boundingInfo.boundingBox);
  34167. };
  34168. /**
  34169. * Returns an object IntersectionInfo.
  34170. */
  34171. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34172. var intersectInfo = null;
  34173. var material = this.getMaterial();
  34174. if (!material) {
  34175. return null;
  34176. }
  34177. switch (material.fillMode) {
  34178. case BABYLON.Material.PointListDrawMode:
  34179. case BABYLON.Material.LineListDrawMode:
  34180. case BABYLON.Material.LineLoopDrawMode:
  34181. case BABYLON.Material.LineStripDrawMode:
  34182. case BABYLON.Material.TriangleFanDrawMode:
  34183. case BABYLON.Material.TriangleStripDrawMode:
  34184. return null;
  34185. }
  34186. // LineMesh first as it's also a Mesh...
  34187. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34188. var lineMesh = this._mesh;
  34189. // Line test
  34190. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34191. var p0 = positions[indices[index]];
  34192. var p1 = positions[indices[index + 1]];
  34193. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34194. if (length < 0) {
  34195. continue;
  34196. }
  34197. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34198. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34199. if (fastCheck) {
  34200. break;
  34201. }
  34202. }
  34203. }
  34204. }
  34205. else {
  34206. // Triangles test
  34207. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34208. var p0 = positions[indices[index]];
  34209. var p1 = positions[indices[index + 1]];
  34210. var p2 = positions[indices[index + 2]];
  34211. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34212. if (currentIntersectInfo) {
  34213. if (currentIntersectInfo.distance < 0) {
  34214. continue;
  34215. }
  34216. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34217. intersectInfo = currentIntersectInfo;
  34218. intersectInfo.faceId = index / 3;
  34219. if (fastCheck) {
  34220. break;
  34221. }
  34222. }
  34223. }
  34224. }
  34225. }
  34226. return intersectInfo;
  34227. };
  34228. SubMesh.prototype._rebuild = function () {
  34229. if (this._linesIndexBuffer) {
  34230. this._linesIndexBuffer = null;
  34231. }
  34232. };
  34233. // Clone
  34234. /**
  34235. * Creates a new Submesh from the passed Mesh.
  34236. */
  34237. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34238. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34239. if (!this.IsGlobal) {
  34240. var boundingInfo = this.getBoundingInfo();
  34241. if (!boundingInfo) {
  34242. return result;
  34243. }
  34244. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34245. }
  34246. return result;
  34247. };
  34248. // Dispose
  34249. /**
  34250. * Disposes the Submesh.
  34251. * Returns nothing.
  34252. */
  34253. SubMesh.prototype.dispose = function () {
  34254. if (this._linesIndexBuffer) {
  34255. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34256. this._linesIndexBuffer = null;
  34257. }
  34258. // Remove from mesh
  34259. var index = this._mesh.subMeshes.indexOf(this);
  34260. this._mesh.subMeshes.splice(index, 1);
  34261. };
  34262. // Statics
  34263. /**
  34264. * Creates a new Submesh from the passed parameters :
  34265. * - materialIndex (integer) : the index of the main mesh material.
  34266. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34267. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34268. * - mesh (Mesh) : the main mesh to create the submesh from.
  34269. * - renderingMesh (optional Mesh) : rendering mesh.
  34270. */
  34271. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34272. var minVertexIndex = Number.MAX_VALUE;
  34273. var maxVertexIndex = -Number.MAX_VALUE;
  34274. renderingMesh = (renderingMesh || mesh);
  34275. var indices = renderingMesh.getIndices();
  34276. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34277. var vertexIndex = indices[index];
  34278. if (vertexIndex < minVertexIndex)
  34279. minVertexIndex = vertexIndex;
  34280. if (vertexIndex > maxVertexIndex)
  34281. maxVertexIndex = vertexIndex;
  34282. }
  34283. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34284. };
  34285. return SubMesh;
  34286. }(BaseSubMesh));
  34287. BABYLON.SubMesh = SubMesh;
  34288. })(BABYLON || (BABYLON = {}));
  34289. //# sourceMappingURL=babylon.subMesh.js.map
  34290. var __assign = (this && this.__assign) || Object.assign || function(t) {
  34291. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34292. s = arguments[i];
  34293. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34294. t[p] = s[p];
  34295. }
  34296. return t;
  34297. };
  34298. var BABYLON;
  34299. (function (BABYLON) {
  34300. /**
  34301. * Manages the defines for the Material
  34302. */
  34303. var MaterialDefines = /** @class */ (function () {
  34304. function MaterialDefines() {
  34305. this._isDirty = true;
  34306. /** @hidden */
  34307. this._areLightsDirty = true;
  34308. /** @hidden */
  34309. this._areAttributesDirty = true;
  34310. /** @hidden */
  34311. this._areTexturesDirty = true;
  34312. /** @hidden */
  34313. this._areFresnelDirty = true;
  34314. /** @hidden */
  34315. this._areMiscDirty = true;
  34316. /** @hidden */
  34317. this._areImageProcessingDirty = true;
  34318. /** @hidden */
  34319. this._normals = false;
  34320. /** @hidden */
  34321. this._uvs = false;
  34322. /** @hidden */
  34323. this._needNormals = false;
  34324. /** @hidden */
  34325. this._needUVs = false;
  34326. }
  34327. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34328. /**
  34329. * Specifies if the material needs to be re-calculated
  34330. */
  34331. get: function () {
  34332. return this._isDirty;
  34333. },
  34334. enumerable: true,
  34335. configurable: true
  34336. });
  34337. /**
  34338. * Marks the material to indicate that it has been re-calculated
  34339. */
  34340. MaterialDefines.prototype.markAsProcessed = function () {
  34341. this._isDirty = false;
  34342. this._areAttributesDirty = false;
  34343. this._areTexturesDirty = false;
  34344. this._areFresnelDirty = false;
  34345. this._areLightsDirty = false;
  34346. this._areMiscDirty = false;
  34347. this._areImageProcessingDirty = false;
  34348. };
  34349. /**
  34350. * Marks the material to indicate that it needs to be re-calculated
  34351. */
  34352. MaterialDefines.prototype.markAsUnprocessed = function () {
  34353. this._isDirty = true;
  34354. };
  34355. /**
  34356. * Marks the material to indicate all of its defines need to be re-calculated
  34357. */
  34358. MaterialDefines.prototype.markAllAsDirty = function () {
  34359. this._areTexturesDirty = true;
  34360. this._areAttributesDirty = true;
  34361. this._areLightsDirty = true;
  34362. this._areFresnelDirty = true;
  34363. this._areMiscDirty = true;
  34364. this._areImageProcessingDirty = true;
  34365. this._isDirty = true;
  34366. };
  34367. /**
  34368. * Marks the material to indicate that image processing needs to be re-calculated
  34369. */
  34370. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34371. this._areImageProcessingDirty = true;
  34372. this._isDirty = true;
  34373. };
  34374. /**
  34375. * Marks the material to indicate the lights need to be re-calculated
  34376. */
  34377. MaterialDefines.prototype.markAsLightDirty = function () {
  34378. this._areLightsDirty = true;
  34379. this._isDirty = true;
  34380. };
  34381. /**
  34382. * Marks the attribute state as changed
  34383. */
  34384. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34385. this._areAttributesDirty = true;
  34386. this._isDirty = true;
  34387. };
  34388. /**
  34389. * Marks the texture state as changed
  34390. */
  34391. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34392. this._areTexturesDirty = true;
  34393. this._isDirty = true;
  34394. };
  34395. /**
  34396. * Marks the fresnel state as changed
  34397. */
  34398. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34399. this._areFresnelDirty = true;
  34400. this._isDirty = true;
  34401. };
  34402. /**
  34403. * Marks the misc state as changed
  34404. */
  34405. MaterialDefines.prototype.markAsMiscDirty = function () {
  34406. this._areMiscDirty = true;
  34407. this._isDirty = true;
  34408. };
  34409. /**
  34410. * Rebuilds the material defines
  34411. */
  34412. MaterialDefines.prototype.rebuild = function () {
  34413. if (this._keys) {
  34414. delete this._keys;
  34415. }
  34416. this._keys = [];
  34417. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34418. var key = _a[_i];
  34419. if (key[0] === "_") {
  34420. continue;
  34421. }
  34422. this._keys.push(key);
  34423. }
  34424. };
  34425. /**
  34426. * Specifies if two material defines are equal
  34427. * @param other - A material define instance to compare to
  34428. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34429. */
  34430. MaterialDefines.prototype.isEqual = function (other) {
  34431. if (this._keys.length !== other._keys.length) {
  34432. return false;
  34433. }
  34434. for (var index = 0; index < this._keys.length; index++) {
  34435. var prop = this._keys[index];
  34436. if (this[prop] !== other[prop]) {
  34437. return false;
  34438. }
  34439. }
  34440. return true;
  34441. };
  34442. /**
  34443. * Clones this instance's defines to another instance
  34444. * @param other - material defines to clone values to
  34445. */
  34446. MaterialDefines.prototype.cloneTo = function (other) {
  34447. if (this._keys.length !== other._keys.length) {
  34448. other._keys = this._keys.slice(0);
  34449. }
  34450. for (var index = 0; index < this._keys.length; index++) {
  34451. var prop = this._keys[index];
  34452. other[prop] = this[prop];
  34453. }
  34454. };
  34455. /**
  34456. * Resets the material define values
  34457. */
  34458. MaterialDefines.prototype.reset = function () {
  34459. for (var index = 0; index < this._keys.length; index++) {
  34460. var prop = this._keys[index];
  34461. var type = typeof this[prop];
  34462. switch (type) {
  34463. case "number":
  34464. this[prop] = 0;
  34465. break;
  34466. case "string":
  34467. this[prop] = "";
  34468. break;
  34469. default:
  34470. this[prop] = false;
  34471. break;
  34472. }
  34473. }
  34474. };
  34475. /**
  34476. * Converts the material define values to a string
  34477. * @returns - String of material define information
  34478. */
  34479. MaterialDefines.prototype.toString = function () {
  34480. var result = "";
  34481. for (var index = 0; index < this._keys.length; index++) {
  34482. var prop = this._keys[index];
  34483. var value = this[prop];
  34484. var type = typeof value;
  34485. switch (type) {
  34486. case "number":
  34487. case "string":
  34488. result += "#define " + prop + " " + value + "\n";
  34489. break;
  34490. default:
  34491. if (value) {
  34492. result += "#define " + prop + "\n";
  34493. }
  34494. break;
  34495. }
  34496. }
  34497. return result;
  34498. };
  34499. return MaterialDefines;
  34500. }());
  34501. BABYLON.MaterialDefines = MaterialDefines;
  34502. /**
  34503. * Base class for the main features of a material in Babylon.js
  34504. */
  34505. var Material = /** @class */ (function () {
  34506. /**
  34507. * Creates a material instance
  34508. * @param name defines the name of the material
  34509. * @param scene defines the scene to reference
  34510. * @param doNotAdd specifies if the material should be added to the scene
  34511. */
  34512. function Material(name, scene, doNotAdd) {
  34513. /**
  34514. * Specifies if the ready state should be checked on each call
  34515. */
  34516. this.checkReadyOnEveryCall = false;
  34517. /**
  34518. * Specifies if the ready state should be checked once
  34519. */
  34520. this.checkReadyOnlyOnce = false;
  34521. /**
  34522. * The state of the material
  34523. */
  34524. this.state = "";
  34525. /**
  34526. * The alpha value of the material
  34527. */
  34528. this._alpha = 1.0;
  34529. /**
  34530. * Specifies if back face culling is enabled
  34531. */
  34532. this._backFaceCulling = true;
  34533. /**
  34534. * Specifies if the material should be serialized
  34535. */
  34536. this.doNotSerialize = false;
  34537. /**
  34538. * Specifies if the effect should be stored on sub meshes
  34539. */
  34540. this.storeEffectOnSubMeshes = false;
  34541. /**
  34542. * An event triggered when the material is disposed
  34543. */
  34544. this.onDisposeObservable = new BABYLON.Observable();
  34545. /**
  34546. * An event triggered when the material is bound
  34547. */
  34548. this.onBindObservable = new BABYLON.Observable();
  34549. /**
  34550. * An event triggered when the material is unbound
  34551. */
  34552. this.onUnBindObservable = new BABYLON.Observable();
  34553. /**
  34554. * Stores the value of the alpha mode
  34555. */
  34556. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  34557. /**
  34558. * Stores the state of the need depth pre-pass value
  34559. */
  34560. this._needDepthPrePass = false;
  34561. /**
  34562. * Specifies if depth writing should be disabled
  34563. */
  34564. this.disableDepthWrite = false;
  34565. /**
  34566. * Specifies if depth writing should be forced
  34567. */
  34568. this.forceDepthWrite = false;
  34569. /**
  34570. * Specifies if there should be a separate pass for culling
  34571. */
  34572. this.separateCullingPass = false;
  34573. /**
  34574. * Stores the state specifing if fog should be enabled
  34575. */
  34576. this._fogEnabled = true;
  34577. /**
  34578. * Stores the size of points
  34579. */
  34580. this.pointSize = 1.0;
  34581. /**
  34582. * Stores the z offset value
  34583. */
  34584. this.zOffset = 0;
  34585. /**
  34586. * Specifies if the material was previously ready
  34587. */
  34588. this._wasPreviouslyReady = false;
  34589. /**
  34590. * Stores the fill mode state
  34591. */
  34592. this._fillMode = Material.TriangleFillMode;
  34593. this.name = name;
  34594. this.id = name || BABYLON.Tools.RandomId();
  34595. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  34596. if (this._scene.useRightHandedSystem) {
  34597. this.sideOrientation = Material.ClockWiseSideOrientation;
  34598. }
  34599. else {
  34600. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  34601. }
  34602. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  34603. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  34604. if (!doNotAdd) {
  34605. this._scene.materials.push(this);
  34606. }
  34607. }
  34608. Object.defineProperty(Material, "TriangleFillMode", {
  34609. /**
  34610. * Returns the triangle fill mode
  34611. */
  34612. get: function () {
  34613. return Material._TriangleFillMode;
  34614. },
  34615. enumerable: true,
  34616. configurable: true
  34617. });
  34618. Object.defineProperty(Material, "WireFrameFillMode", {
  34619. /**
  34620. * Returns the wireframe mode
  34621. */
  34622. get: function () {
  34623. return Material._WireFrameFillMode;
  34624. },
  34625. enumerable: true,
  34626. configurable: true
  34627. });
  34628. Object.defineProperty(Material, "PointFillMode", {
  34629. /**
  34630. * Returns the point fill mode
  34631. */
  34632. get: function () {
  34633. return Material._PointFillMode;
  34634. },
  34635. enumerable: true,
  34636. configurable: true
  34637. });
  34638. Object.defineProperty(Material, "PointListDrawMode", {
  34639. /**
  34640. * Returns the point list draw mode
  34641. */
  34642. get: function () {
  34643. return Material._PointListDrawMode;
  34644. },
  34645. enumerable: true,
  34646. configurable: true
  34647. });
  34648. Object.defineProperty(Material, "LineListDrawMode", {
  34649. /**
  34650. * Returns the line list draw mode
  34651. */
  34652. get: function () {
  34653. return Material._LineListDrawMode;
  34654. },
  34655. enumerable: true,
  34656. configurable: true
  34657. });
  34658. Object.defineProperty(Material, "LineLoopDrawMode", {
  34659. /**
  34660. * Returns the line loop draw mode
  34661. */
  34662. get: function () {
  34663. return Material._LineLoopDrawMode;
  34664. },
  34665. enumerable: true,
  34666. configurable: true
  34667. });
  34668. Object.defineProperty(Material, "LineStripDrawMode", {
  34669. /**
  34670. * Returns the line strip draw mode
  34671. */
  34672. get: function () {
  34673. return Material._LineStripDrawMode;
  34674. },
  34675. enumerable: true,
  34676. configurable: true
  34677. });
  34678. Object.defineProperty(Material, "TriangleStripDrawMode", {
  34679. /**
  34680. * Returns the triangle strip draw mode
  34681. */
  34682. get: function () {
  34683. return Material._TriangleStripDrawMode;
  34684. },
  34685. enumerable: true,
  34686. configurable: true
  34687. });
  34688. Object.defineProperty(Material, "TriangleFanDrawMode", {
  34689. /**
  34690. * Returns the triangle fan draw mode
  34691. */
  34692. get: function () {
  34693. return Material._TriangleFanDrawMode;
  34694. },
  34695. enumerable: true,
  34696. configurable: true
  34697. });
  34698. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  34699. /**
  34700. * Returns the clock-wise side orientation
  34701. */
  34702. get: function () {
  34703. return Material._ClockWiseSideOrientation;
  34704. },
  34705. enumerable: true,
  34706. configurable: true
  34707. });
  34708. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  34709. /**
  34710. * Returns the counter clock-wise side orientation
  34711. */
  34712. get: function () {
  34713. return Material._CounterClockWiseSideOrientation;
  34714. },
  34715. enumerable: true,
  34716. configurable: true
  34717. });
  34718. Object.defineProperty(Material, "TextureDirtyFlag", {
  34719. /**
  34720. * Returns the dirty texture flag value
  34721. */
  34722. get: function () {
  34723. return Material._TextureDirtyFlag;
  34724. },
  34725. enumerable: true,
  34726. configurable: true
  34727. });
  34728. Object.defineProperty(Material, "LightDirtyFlag", {
  34729. /**
  34730. * Returns the dirty light flag value
  34731. */
  34732. get: function () {
  34733. return Material._LightDirtyFlag;
  34734. },
  34735. enumerable: true,
  34736. configurable: true
  34737. });
  34738. Object.defineProperty(Material, "FresnelDirtyFlag", {
  34739. /**
  34740. * Returns the dirty fresnel flag value
  34741. */
  34742. get: function () {
  34743. return Material._FresnelDirtyFlag;
  34744. },
  34745. enumerable: true,
  34746. configurable: true
  34747. });
  34748. Object.defineProperty(Material, "AttributesDirtyFlag", {
  34749. /**
  34750. * Returns the dirty attributes flag value
  34751. */
  34752. get: function () {
  34753. return Material._AttributesDirtyFlag;
  34754. },
  34755. enumerable: true,
  34756. configurable: true
  34757. });
  34758. Object.defineProperty(Material, "MiscDirtyFlag", {
  34759. /**
  34760. * Returns the dirty misc flag value
  34761. */
  34762. get: function () {
  34763. return Material._MiscDirtyFlag;
  34764. },
  34765. enumerable: true,
  34766. configurable: true
  34767. });
  34768. Object.defineProperty(Material.prototype, "alpha", {
  34769. /**
  34770. * Gets the alpha value of the material
  34771. */
  34772. get: function () {
  34773. return this._alpha;
  34774. },
  34775. /**
  34776. * Sets the alpha value of the material
  34777. */
  34778. set: function (value) {
  34779. if (this._alpha === value) {
  34780. return;
  34781. }
  34782. this._alpha = value;
  34783. this.markAsDirty(Material.MiscDirtyFlag);
  34784. },
  34785. enumerable: true,
  34786. configurable: true
  34787. });
  34788. Object.defineProperty(Material.prototype, "backFaceCulling", {
  34789. /**
  34790. * Gets the back-face culling state
  34791. */
  34792. get: function () {
  34793. return this._backFaceCulling;
  34794. },
  34795. /**
  34796. * Sets the back-face culling state
  34797. */
  34798. set: function (value) {
  34799. if (this._backFaceCulling === value) {
  34800. return;
  34801. }
  34802. this._backFaceCulling = value;
  34803. this.markAsDirty(Material.TextureDirtyFlag);
  34804. },
  34805. enumerable: true,
  34806. configurable: true
  34807. });
  34808. Object.defineProperty(Material.prototype, "onDispose", {
  34809. /**
  34810. * Called during a dispose event
  34811. */
  34812. set: function (callback) {
  34813. if (this._onDisposeObserver) {
  34814. this.onDisposeObservable.remove(this._onDisposeObserver);
  34815. }
  34816. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  34817. },
  34818. enumerable: true,
  34819. configurable: true
  34820. });
  34821. Object.defineProperty(Material.prototype, "onBind", {
  34822. /**
  34823. * Called during a bind event
  34824. */
  34825. set: function (callback) {
  34826. if (this._onBindObserver) {
  34827. this.onBindObservable.remove(this._onBindObserver);
  34828. }
  34829. this._onBindObserver = this.onBindObservable.add(callback);
  34830. },
  34831. enumerable: true,
  34832. configurable: true
  34833. });
  34834. Object.defineProperty(Material.prototype, "alphaMode", {
  34835. /**
  34836. * Gets the value of the alpha mode
  34837. */
  34838. get: function () {
  34839. return this._alphaMode;
  34840. },
  34841. /**
  34842. * Sets the value of the alpha mode.
  34843. *
  34844. * | Value | Type | Description |
  34845. * | --- | --- | --- |
  34846. * | 0 | ALPHA_DISABLE | |
  34847. * | 1 | ALPHA_ADD | |
  34848. * | 2 | ALPHA_COMBINE | |
  34849. * | 3 | ALPHA_SUBTRACT | |
  34850. * | 4 | ALPHA_MULTIPLY | |
  34851. * | 5 | ALPHA_MAXIMIZED | |
  34852. * | 6 | ALPHA_ONEONE | |
  34853. * | 7 | ALPHA_PREMULTIPLIED | |
  34854. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  34855. * | 9 | ALPHA_INTERPOLATE | |
  34856. * | 10 | ALPHA_SCREENMODE | |
  34857. *
  34858. */
  34859. set: function (value) {
  34860. if (this._alphaMode === value) {
  34861. return;
  34862. }
  34863. this._alphaMode = value;
  34864. this.markAsDirty(Material.TextureDirtyFlag);
  34865. },
  34866. enumerable: true,
  34867. configurable: true
  34868. });
  34869. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  34870. /**
  34871. * Gets the depth pre-pass value
  34872. */
  34873. get: function () {
  34874. return this._needDepthPrePass;
  34875. },
  34876. /**
  34877. * Sets the need depth pre-pass value
  34878. */
  34879. set: function (value) {
  34880. if (this._needDepthPrePass === value) {
  34881. return;
  34882. }
  34883. this._needDepthPrePass = value;
  34884. if (this._needDepthPrePass) {
  34885. this.checkReadyOnEveryCall = true;
  34886. }
  34887. },
  34888. enumerable: true,
  34889. configurable: true
  34890. });
  34891. Object.defineProperty(Material.prototype, "fogEnabled", {
  34892. /**
  34893. * Gets the value of the fog enabled state
  34894. */
  34895. get: function () {
  34896. return this._fogEnabled;
  34897. },
  34898. /**
  34899. * Sets the state for enabling fog
  34900. */
  34901. set: function (value) {
  34902. if (this._fogEnabled === value) {
  34903. return;
  34904. }
  34905. this._fogEnabled = value;
  34906. this.markAsDirty(Material.MiscDirtyFlag);
  34907. },
  34908. enumerable: true,
  34909. configurable: true
  34910. });
  34911. Object.defineProperty(Material.prototype, "wireframe", {
  34912. /**
  34913. * Gets a value specifying if wireframe mode is enabled
  34914. */
  34915. get: function () {
  34916. switch (this._fillMode) {
  34917. case Material.WireFrameFillMode:
  34918. case Material.LineListDrawMode:
  34919. case Material.LineLoopDrawMode:
  34920. case Material.LineStripDrawMode:
  34921. return true;
  34922. }
  34923. return this._scene.forceWireframe;
  34924. },
  34925. /**
  34926. * Sets the state of wireframe mode
  34927. */
  34928. set: function (value) {
  34929. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  34930. },
  34931. enumerable: true,
  34932. configurable: true
  34933. });
  34934. Object.defineProperty(Material.prototype, "pointsCloud", {
  34935. /**
  34936. * Gets the value specifying if point clouds are enabled
  34937. */
  34938. get: function () {
  34939. switch (this._fillMode) {
  34940. case Material.PointFillMode:
  34941. case Material.PointListDrawMode:
  34942. return true;
  34943. }
  34944. return this._scene.forcePointsCloud;
  34945. },
  34946. /**
  34947. * Sets the state of point cloud mode
  34948. */
  34949. set: function (value) {
  34950. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  34951. },
  34952. enumerable: true,
  34953. configurable: true
  34954. });
  34955. Object.defineProperty(Material.prototype, "fillMode", {
  34956. /**
  34957. * Gets the material fill mode
  34958. */
  34959. get: function () {
  34960. return this._fillMode;
  34961. },
  34962. /**
  34963. * Sets the material fill mode
  34964. */
  34965. set: function (value) {
  34966. if (this._fillMode === value) {
  34967. return;
  34968. }
  34969. this._fillMode = value;
  34970. this.markAsDirty(Material.MiscDirtyFlag);
  34971. },
  34972. enumerable: true,
  34973. configurable: true
  34974. });
  34975. /**
  34976. * Returns a string representation of the current material
  34977. * @param fullDetails defines a boolean indicating which levels of logging is desired
  34978. * @returns a string with material information
  34979. */
  34980. Material.prototype.toString = function (fullDetails) {
  34981. var ret = "Name: " + this.name;
  34982. if (fullDetails) {
  34983. }
  34984. return ret;
  34985. };
  34986. /**
  34987. * Gets the class name of the material
  34988. * @returns a string with the class name of the material
  34989. */
  34990. Material.prototype.getClassName = function () {
  34991. return "Material";
  34992. };
  34993. Object.defineProperty(Material.prototype, "isFrozen", {
  34994. /**
  34995. * Specifies if updates for the material been locked
  34996. */
  34997. get: function () {
  34998. return this.checkReadyOnlyOnce;
  34999. },
  35000. enumerable: true,
  35001. configurable: true
  35002. });
  35003. /**
  35004. * Locks updates for the material
  35005. */
  35006. Material.prototype.freeze = function () {
  35007. this.checkReadyOnlyOnce = true;
  35008. };
  35009. /**
  35010. * Unlocks updates for the material
  35011. */
  35012. Material.prototype.unfreeze = function () {
  35013. this.checkReadyOnlyOnce = false;
  35014. };
  35015. /**
  35016. * Specifies if the material is ready to be used
  35017. * @param mesh defines the mesh to check
  35018. * @param useInstances specifies if instances should be used
  35019. * @returns a boolean indicating if the material is ready to be used
  35020. */
  35021. Material.prototype.isReady = function (mesh, useInstances) {
  35022. return true;
  35023. };
  35024. /**
  35025. * Specifies that the submesh is ready to be used
  35026. * @param mesh defines the mesh to check
  35027. * @param subMesh defines which submesh to check
  35028. * @param useInstances specifies that instances should be used
  35029. * @returns a boolean indicating that the submesh is ready or not
  35030. */
  35031. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35032. return false;
  35033. };
  35034. /**
  35035. * Returns the material effect
  35036. * @returns the effect associated with the material
  35037. */
  35038. Material.prototype.getEffect = function () {
  35039. return this._effect;
  35040. };
  35041. /**
  35042. * Returns the current scene
  35043. * @returns a Scene
  35044. */
  35045. Material.prototype.getScene = function () {
  35046. return this._scene;
  35047. };
  35048. /**
  35049. * Specifies if the material will require alpha blending
  35050. * @returns a boolean specifying if alpha blending is needed
  35051. */
  35052. Material.prototype.needAlphaBlending = function () {
  35053. return (this.alpha < 1.0);
  35054. };
  35055. /**
  35056. * Specifies if the mesh will require alpha blending
  35057. * @param mesh defines the mesh to check
  35058. * @returns a boolean specifying if alpha blending is needed for the mesh
  35059. */
  35060. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  35061. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  35062. };
  35063. /**
  35064. * Specifies if this material should be rendered in alpha test mode
  35065. * @returns a boolean specifying if an alpha test is needed.
  35066. */
  35067. Material.prototype.needAlphaTesting = function () {
  35068. return false;
  35069. };
  35070. /**
  35071. * Gets the texture used for the alpha test
  35072. * @returns the texture to use for alpha testing
  35073. */
  35074. Material.prototype.getAlphaTestTexture = function () {
  35075. return null;
  35076. };
  35077. /**
  35078. * Marks the material to indicate that it needs to be re-calculated
  35079. */
  35080. Material.prototype.markDirty = function () {
  35081. this._wasPreviouslyReady = false;
  35082. };
  35083. /** @hidden */
  35084. Material.prototype._preBind = function (effect, overrideOrientation) {
  35085. if (overrideOrientation === void 0) { overrideOrientation = null; }
  35086. var engine = this._scene.getEngine();
  35087. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  35088. var reverse = orientation === Material.ClockWiseSideOrientation;
  35089. engine.enableEffect(effect ? effect : this._effect);
  35090. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  35091. return reverse;
  35092. };
  35093. /**
  35094. * Binds the material to the mesh
  35095. * @param world defines the world transformation matrix
  35096. * @param mesh defines the mesh to bind the material to
  35097. */
  35098. Material.prototype.bind = function (world, mesh) {
  35099. };
  35100. /**
  35101. * Binds the submesh to the material
  35102. * @param world defines the world transformation matrix
  35103. * @param mesh defines the mesh containing the submesh
  35104. * @param subMesh defines the submesh to bind the material to
  35105. */
  35106. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35107. };
  35108. /**
  35109. * Binds the world matrix to the material
  35110. * @param world defines the world transformation matrix
  35111. */
  35112. Material.prototype.bindOnlyWorldMatrix = function (world) {
  35113. };
  35114. /**
  35115. * Binds the scene's uniform buffer to the effect.
  35116. * @param effect defines the effect to bind to the scene uniform buffer
  35117. * @param sceneUbo defines the uniform buffer storing scene data
  35118. */
  35119. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35120. sceneUbo.bindToEffect(effect, "Scene");
  35121. };
  35122. /**
  35123. * Binds the view matrix to the effect
  35124. * @param effect defines the effect to bind the view matrix to
  35125. */
  35126. Material.prototype.bindView = function (effect) {
  35127. if (!this._useUBO) {
  35128. effect.setMatrix("view", this.getScene().getViewMatrix());
  35129. }
  35130. else {
  35131. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35132. }
  35133. };
  35134. /**
  35135. * Binds the view projection matrix to the effect
  35136. * @param effect defines the effect to bind the view projection matrix to
  35137. */
  35138. Material.prototype.bindViewProjection = function (effect) {
  35139. if (!this._useUBO) {
  35140. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35141. }
  35142. else {
  35143. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35144. }
  35145. };
  35146. /**
  35147. * Specifies if material alpha testing should be turned on for the mesh
  35148. * @param mesh defines the mesh to check
  35149. */
  35150. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35151. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35152. };
  35153. /**
  35154. * Processes to execute after binding the material to a mesh
  35155. * @param mesh defines the rendered mesh
  35156. */
  35157. Material.prototype._afterBind = function (mesh) {
  35158. this._scene._cachedMaterial = this;
  35159. if (mesh) {
  35160. this._scene._cachedVisibility = mesh.visibility;
  35161. }
  35162. else {
  35163. this._scene._cachedVisibility = 1;
  35164. }
  35165. if (mesh) {
  35166. this.onBindObservable.notifyObservers(mesh);
  35167. }
  35168. if (this.disableDepthWrite) {
  35169. var engine = this._scene.getEngine();
  35170. this._cachedDepthWriteState = engine.getDepthWrite();
  35171. engine.setDepthWrite(false);
  35172. }
  35173. };
  35174. /**
  35175. * Unbinds the material from the mesh
  35176. */
  35177. Material.prototype.unbind = function () {
  35178. this.onUnBindObservable.notifyObservers(this);
  35179. if (this.disableDepthWrite) {
  35180. var engine = this._scene.getEngine();
  35181. engine.setDepthWrite(this._cachedDepthWriteState);
  35182. }
  35183. };
  35184. /**
  35185. * Gets the active textures from the material
  35186. * @returns an array of textures
  35187. */
  35188. Material.prototype.getActiveTextures = function () {
  35189. return [];
  35190. };
  35191. /**
  35192. * Specifies if the material uses a texture
  35193. * @param texture defines the texture to check against the material
  35194. * @returns a boolean specifying if the material uses the texture
  35195. */
  35196. Material.prototype.hasTexture = function (texture) {
  35197. return false;
  35198. };
  35199. /**
  35200. * Makes a duplicate of the material, and gives it a new name
  35201. * @param name defines the new name for the duplicated material
  35202. * @returns the cloned material
  35203. */
  35204. Material.prototype.clone = function (name) {
  35205. return null;
  35206. };
  35207. /**
  35208. * Gets the meshes bound to the material
  35209. * @returns an array of meshes bound to the material
  35210. */
  35211. Material.prototype.getBindedMeshes = function () {
  35212. var result = new Array();
  35213. for (var index = 0; index < this._scene.meshes.length; index++) {
  35214. var mesh = this._scene.meshes[index];
  35215. if (mesh.material === this) {
  35216. result.push(mesh);
  35217. }
  35218. }
  35219. return result;
  35220. };
  35221. /**
  35222. * Force shader compilation
  35223. * @param mesh defines the mesh associated with this material
  35224. * @param onCompiled defines a function to execute once the material is compiled
  35225. * @param options defines the options to configure the compilation
  35226. */
  35227. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35228. var _this = this;
  35229. var localOptions = __assign({ clipPlane: false }, options);
  35230. var subMesh = new BABYLON.BaseSubMesh();
  35231. var scene = this.getScene();
  35232. var checkReady = function () {
  35233. if (!_this._scene || !_this._scene.getEngine()) {
  35234. return;
  35235. }
  35236. if (subMesh._materialDefines) {
  35237. subMesh._materialDefines._renderId = -1;
  35238. }
  35239. var clipPlaneState = scene.clipPlane;
  35240. if (localOptions.clipPlane) {
  35241. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35242. }
  35243. if (_this.storeEffectOnSubMeshes) {
  35244. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35245. if (onCompiled) {
  35246. onCompiled(_this);
  35247. }
  35248. }
  35249. else {
  35250. setTimeout(checkReady, 16);
  35251. }
  35252. }
  35253. else {
  35254. if (_this.isReady(mesh)) {
  35255. if (onCompiled) {
  35256. onCompiled(_this);
  35257. }
  35258. }
  35259. else {
  35260. setTimeout(checkReady, 16);
  35261. }
  35262. }
  35263. if (localOptions.clipPlane) {
  35264. scene.clipPlane = clipPlaneState;
  35265. }
  35266. };
  35267. checkReady();
  35268. };
  35269. /**
  35270. * Force shader compilation
  35271. * @param mesh defines the mesh that will use this material
  35272. * @param options defines additional options for compiling the shaders
  35273. * @returns a promise that resolves when the compilation completes
  35274. */
  35275. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35276. var _this = this;
  35277. return new Promise(function (resolve) {
  35278. _this.forceCompilation(mesh, function () {
  35279. resolve();
  35280. }, options);
  35281. });
  35282. };
  35283. /**
  35284. * Marks a define in the material to indicate that it needs to be re-computed
  35285. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35286. */
  35287. Material.prototype.markAsDirty = function (flag) {
  35288. if (flag & Material.TextureDirtyFlag) {
  35289. this._markAllSubMeshesAsTexturesDirty();
  35290. }
  35291. if (flag & Material.LightDirtyFlag) {
  35292. this._markAllSubMeshesAsLightsDirty();
  35293. }
  35294. if (flag & Material.FresnelDirtyFlag) {
  35295. this._markAllSubMeshesAsFresnelDirty();
  35296. }
  35297. if (flag & Material.AttributesDirtyFlag) {
  35298. this._markAllSubMeshesAsAttributesDirty();
  35299. }
  35300. if (flag & Material.MiscDirtyFlag) {
  35301. this._markAllSubMeshesAsMiscDirty();
  35302. }
  35303. this.getScene().resetCachedMaterial();
  35304. };
  35305. /**
  35306. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35307. * @param func defines a function which checks material defines against the submeshes
  35308. */
  35309. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35310. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35311. var mesh = _a[_i];
  35312. if (!mesh.subMeshes) {
  35313. continue;
  35314. }
  35315. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35316. var subMesh = _c[_b];
  35317. if (subMesh.getMaterial() !== this) {
  35318. continue;
  35319. }
  35320. if (!subMesh._materialDefines) {
  35321. continue;
  35322. }
  35323. func(subMesh._materialDefines);
  35324. }
  35325. }
  35326. };
  35327. /**
  35328. * Indicates that image processing needs to be re-calculated for all submeshes
  35329. */
  35330. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35331. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35332. };
  35333. /**
  35334. * Indicates that textures need to be re-calculated for all submeshes
  35335. */
  35336. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35337. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35338. };
  35339. /**
  35340. * Indicates that fresnel needs to be re-calculated for all submeshes
  35341. */
  35342. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35343. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35344. };
  35345. /**
  35346. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35347. */
  35348. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35349. this._markAllSubMeshesAsDirty(function (defines) {
  35350. defines.markAsFresnelDirty();
  35351. defines.markAsMiscDirty();
  35352. });
  35353. };
  35354. /**
  35355. * Indicates that lights need to be re-calculated for all submeshes
  35356. */
  35357. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35358. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35359. };
  35360. /**
  35361. * Indicates that attributes need to be re-calculated for all submeshes
  35362. */
  35363. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35364. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35365. };
  35366. /**
  35367. * Indicates that misc needs to be re-calculated for all submeshes
  35368. */
  35369. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35370. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35371. };
  35372. /**
  35373. * Indicates that textures and misc need to be re-calculated for all submeshes
  35374. */
  35375. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35376. this._markAllSubMeshesAsDirty(function (defines) {
  35377. defines.markAsTexturesDirty();
  35378. defines.markAsMiscDirty();
  35379. });
  35380. };
  35381. /**
  35382. * Disposes the material
  35383. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35384. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35385. */
  35386. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35387. // Animations
  35388. this.getScene().stopAnimation(this);
  35389. this.getScene().freeProcessedMaterials();
  35390. // Remove from scene
  35391. var index = this._scene.materials.indexOf(this);
  35392. if (index >= 0) {
  35393. this._scene.materials.splice(index, 1);
  35394. }
  35395. // Remove from meshes
  35396. for (index = 0; index < this._scene.meshes.length; index++) {
  35397. var mesh = this._scene.meshes[index];
  35398. if (mesh.material === this) {
  35399. mesh.material = null;
  35400. if (mesh.geometry) {
  35401. var geometry = (mesh.geometry);
  35402. if (this.storeEffectOnSubMeshes) {
  35403. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35404. var subMesh = _a[_i];
  35405. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35406. if (forceDisposeEffect && subMesh._materialEffect) {
  35407. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35408. }
  35409. }
  35410. }
  35411. else {
  35412. geometry._releaseVertexArrayObject(this._effect);
  35413. }
  35414. }
  35415. }
  35416. }
  35417. this._uniformBuffer.dispose();
  35418. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35419. if (forceDisposeEffect && this._effect) {
  35420. if (!this.storeEffectOnSubMeshes) {
  35421. this._scene.getEngine()._releaseEffect(this._effect);
  35422. }
  35423. this._effect = null;
  35424. }
  35425. // Callback
  35426. this.onDisposeObservable.notifyObservers(this);
  35427. this.onDisposeObservable.clear();
  35428. this.onBindObservable.clear();
  35429. this.onUnBindObservable.clear();
  35430. };
  35431. /**
  35432. * Serializes this material
  35433. * @returns the serialized material object
  35434. */
  35435. Material.prototype.serialize = function () {
  35436. return BABYLON.SerializationHelper.Serialize(this);
  35437. };
  35438. /**
  35439. * Creates a MultiMaterial from parsed MultiMaterial data.
  35440. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35441. * @param scene defines the hosting scene
  35442. * @returns a new MultiMaterial
  35443. */
  35444. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35445. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35446. multiMaterial.id = parsedMultiMaterial.id;
  35447. if (BABYLON.Tags) {
  35448. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35449. }
  35450. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35451. var subMatId = parsedMultiMaterial.materials[matIndex];
  35452. if (subMatId) {
  35453. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35454. }
  35455. else {
  35456. multiMaterial.subMaterials.push(null);
  35457. }
  35458. }
  35459. return multiMaterial;
  35460. };
  35461. /**
  35462. * Creates a material from parsed material data
  35463. * @param parsedMaterial defines parsed material data
  35464. * @param scene defines the hosting scene
  35465. * @param rootUrl defines the root URL to use to load textures
  35466. * @returns a new material
  35467. */
  35468. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35469. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35470. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35471. }
  35472. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35473. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35474. if (!BABYLON.LegacyPBRMaterial) {
  35475. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35476. return;
  35477. }
  35478. }
  35479. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35480. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35481. };
  35482. // Triangle views
  35483. Material._TriangleFillMode = 0;
  35484. Material._WireFrameFillMode = 1;
  35485. Material._PointFillMode = 2;
  35486. // Draw modes
  35487. Material._PointListDrawMode = 3;
  35488. Material._LineListDrawMode = 4;
  35489. Material._LineLoopDrawMode = 5;
  35490. Material._LineStripDrawMode = 6;
  35491. Material._TriangleStripDrawMode = 7;
  35492. Material._TriangleFanDrawMode = 8;
  35493. /**
  35494. * Stores the clock-wise side orientation
  35495. */
  35496. Material._ClockWiseSideOrientation = 0;
  35497. /**
  35498. * Stores the counter clock-wise side orientation
  35499. */
  35500. Material._CounterClockWiseSideOrientation = 1;
  35501. /**
  35502. * The dirty texture flag value
  35503. */
  35504. Material._TextureDirtyFlag = 1;
  35505. /**
  35506. * The dirty light flag value
  35507. */
  35508. Material._LightDirtyFlag = 2;
  35509. /**
  35510. * The dirty fresnel flag value
  35511. */
  35512. Material._FresnelDirtyFlag = 4;
  35513. /**
  35514. * The dirty attribute flag value
  35515. */
  35516. Material._AttributesDirtyFlag = 8;
  35517. /**
  35518. * The dirty misc flag value
  35519. */
  35520. Material._MiscDirtyFlag = 16;
  35521. __decorate([
  35522. BABYLON.serialize()
  35523. ], Material.prototype, "id", void 0);
  35524. __decorate([
  35525. BABYLON.serialize()
  35526. ], Material.prototype, "name", void 0);
  35527. __decorate([
  35528. BABYLON.serialize()
  35529. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  35530. __decorate([
  35531. BABYLON.serialize()
  35532. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  35533. __decorate([
  35534. BABYLON.serialize()
  35535. ], Material.prototype, "state", void 0);
  35536. __decorate([
  35537. BABYLON.serialize("alpha")
  35538. ], Material.prototype, "_alpha", void 0);
  35539. __decorate([
  35540. BABYLON.serialize("backFaceCulling")
  35541. ], Material.prototype, "_backFaceCulling", void 0);
  35542. __decorate([
  35543. BABYLON.serialize()
  35544. ], Material.prototype, "sideOrientation", void 0);
  35545. __decorate([
  35546. BABYLON.serialize("alphaMode")
  35547. ], Material.prototype, "_alphaMode", void 0);
  35548. __decorate([
  35549. BABYLON.serialize()
  35550. ], Material.prototype, "_needDepthPrePass", void 0);
  35551. __decorate([
  35552. BABYLON.serialize()
  35553. ], Material.prototype, "disableDepthWrite", void 0);
  35554. __decorate([
  35555. BABYLON.serialize()
  35556. ], Material.prototype, "forceDepthWrite", void 0);
  35557. __decorate([
  35558. BABYLON.serialize()
  35559. ], Material.prototype, "separateCullingPass", void 0);
  35560. __decorate([
  35561. BABYLON.serialize("fogEnabled")
  35562. ], Material.prototype, "_fogEnabled", void 0);
  35563. __decorate([
  35564. BABYLON.serialize()
  35565. ], Material.prototype, "pointSize", void 0);
  35566. __decorate([
  35567. BABYLON.serialize()
  35568. ], Material.prototype, "zOffset", void 0);
  35569. __decorate([
  35570. BABYLON.serialize()
  35571. ], Material.prototype, "wireframe", null);
  35572. __decorate([
  35573. BABYLON.serialize()
  35574. ], Material.prototype, "pointsCloud", null);
  35575. __decorate([
  35576. BABYLON.serialize()
  35577. ], Material.prototype, "fillMode", null);
  35578. return Material;
  35579. }());
  35580. BABYLON.Material = Material;
  35581. })(BABYLON || (BABYLON = {}));
  35582. //# sourceMappingURL=babylon.material.js.map
  35583. var BABYLON;
  35584. (function (BABYLON) {
  35585. var UniformBuffer = /** @class */ (function () {
  35586. /**
  35587. * Uniform buffer objects.
  35588. *
  35589. * Handles blocks of uniform on the GPU.
  35590. *
  35591. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  35592. *
  35593. * For more information, please refer to :
  35594. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  35595. */
  35596. function UniformBuffer(engine, data, dynamic) {
  35597. this._engine = engine;
  35598. this._noUBO = !engine.supportsUniformBuffers;
  35599. this._dynamic = dynamic;
  35600. this._data = data || [];
  35601. this._uniformLocations = {};
  35602. this._uniformSizes = {};
  35603. this._uniformLocationPointer = 0;
  35604. this._needSync = false;
  35605. if (this._noUBO) {
  35606. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  35607. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  35608. this.updateFloat = this._updateFloatForEffect;
  35609. this.updateFloat2 = this._updateFloat2ForEffect;
  35610. this.updateFloat3 = this._updateFloat3ForEffect;
  35611. this.updateFloat4 = this._updateFloat4ForEffect;
  35612. this.updateMatrix = this._updateMatrixForEffect;
  35613. this.updateVector3 = this._updateVector3ForEffect;
  35614. this.updateVector4 = this._updateVector4ForEffect;
  35615. this.updateColor3 = this._updateColor3ForEffect;
  35616. this.updateColor4 = this._updateColor4ForEffect;
  35617. }
  35618. else {
  35619. this._engine._uniformBuffers.push(this);
  35620. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  35621. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  35622. this.updateFloat = this._updateFloatForUniform;
  35623. this.updateFloat2 = this._updateFloat2ForUniform;
  35624. this.updateFloat3 = this._updateFloat3ForUniform;
  35625. this.updateFloat4 = this._updateFloat4ForUniform;
  35626. this.updateMatrix = this._updateMatrixForUniform;
  35627. this.updateVector3 = this._updateVector3ForUniform;
  35628. this.updateVector4 = this._updateVector4ForUniform;
  35629. this.updateColor3 = this._updateColor3ForUniform;
  35630. this.updateColor4 = this._updateColor4ForUniform;
  35631. }
  35632. }
  35633. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  35634. // Properties
  35635. /**
  35636. * Indicates if the buffer is using the WebGL2 UBO implementation,
  35637. * or just falling back on setUniformXXX calls.
  35638. */
  35639. get: function () {
  35640. return !this._noUBO;
  35641. },
  35642. enumerable: true,
  35643. configurable: true
  35644. });
  35645. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  35646. /**
  35647. * Indicates if the WebGL underlying uniform buffer is in sync
  35648. * with the javascript cache data.
  35649. */
  35650. get: function () {
  35651. return !this._needSync;
  35652. },
  35653. enumerable: true,
  35654. configurable: true
  35655. });
  35656. /**
  35657. * Indicates if the WebGL underlying uniform buffer is dynamic.
  35658. * Also, a dynamic UniformBuffer will disable cache verification and always
  35659. * update the underlying WebGL uniform buffer to the GPU.
  35660. */
  35661. UniformBuffer.prototype.isDynamic = function () {
  35662. return this._dynamic !== undefined;
  35663. };
  35664. /**
  35665. * The data cache on JS side.
  35666. */
  35667. UniformBuffer.prototype.getData = function () {
  35668. return this._bufferData;
  35669. };
  35670. /**
  35671. * The underlying WebGL Uniform buffer.
  35672. */
  35673. UniformBuffer.prototype.getBuffer = function () {
  35674. return this._buffer;
  35675. };
  35676. /**
  35677. * std140 layout specifies how to align data within an UBO structure.
  35678. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  35679. * for specs.
  35680. */
  35681. UniformBuffer.prototype._fillAlignment = function (size) {
  35682. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  35683. // and 4x4 matrices
  35684. // TODO : change if other types are used
  35685. var alignment;
  35686. if (size <= 2) {
  35687. alignment = size;
  35688. }
  35689. else {
  35690. alignment = 4;
  35691. }
  35692. if ((this._uniformLocationPointer % alignment) !== 0) {
  35693. var oldPointer = this._uniformLocationPointer;
  35694. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  35695. var diff = this._uniformLocationPointer - oldPointer;
  35696. for (var i = 0; i < diff; i++) {
  35697. this._data.push(0);
  35698. }
  35699. }
  35700. };
  35701. /**
  35702. * Adds an uniform in the buffer.
  35703. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  35704. * for the layout to be correct !
  35705. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35706. * @param {number|number[]} size Data size, or data directly.
  35707. */
  35708. UniformBuffer.prototype.addUniform = function (name, size) {
  35709. if (this._noUBO) {
  35710. return;
  35711. }
  35712. if (this._uniformLocations[name] !== undefined) {
  35713. // Already existing uniform
  35714. return;
  35715. }
  35716. // This function must be called in the order of the shader layout !
  35717. // size can be the size of the uniform, or data directly
  35718. var data;
  35719. if (size instanceof Array) {
  35720. data = size;
  35721. size = data.length;
  35722. }
  35723. else {
  35724. size = size;
  35725. data = [];
  35726. // Fill with zeros
  35727. for (var i = 0; i < size; i++) {
  35728. data.push(0);
  35729. }
  35730. }
  35731. this._fillAlignment(size);
  35732. this._uniformSizes[name] = size;
  35733. this._uniformLocations[name] = this._uniformLocationPointer;
  35734. this._uniformLocationPointer += size;
  35735. for (var i = 0; i < size; i++) {
  35736. this._data.push(data[i]);
  35737. }
  35738. this._needSync = true;
  35739. };
  35740. /**
  35741. * Wrapper for addUniform.
  35742. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35743. * @param {Matrix} mat A 4x4 matrix.
  35744. */
  35745. UniformBuffer.prototype.addMatrix = function (name, mat) {
  35746. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  35747. };
  35748. /**
  35749. * Wrapper for addUniform.
  35750. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35751. * @param {number} x
  35752. * @param {number} y
  35753. */
  35754. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  35755. var temp = [x, y];
  35756. this.addUniform(name, temp);
  35757. };
  35758. /**
  35759. * Wrapper for addUniform.
  35760. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35761. * @param {number} x
  35762. * @param {number} y
  35763. * @param {number} z
  35764. */
  35765. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  35766. var temp = [x, y, z];
  35767. this.addUniform(name, temp);
  35768. };
  35769. /**
  35770. * Wrapper for addUniform.
  35771. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35772. * @param {Color3} color
  35773. */
  35774. UniformBuffer.prototype.addColor3 = function (name, color) {
  35775. var temp = new Array();
  35776. color.toArray(temp);
  35777. this.addUniform(name, temp);
  35778. };
  35779. /**
  35780. * Wrapper for addUniform.
  35781. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35782. * @param {Color3} color
  35783. * @param {number} alpha
  35784. */
  35785. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  35786. var temp = new Array();
  35787. color.toArray(temp);
  35788. temp.push(alpha);
  35789. this.addUniform(name, temp);
  35790. };
  35791. /**
  35792. * Wrapper for addUniform.
  35793. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35794. * @param {Vector3} vector
  35795. */
  35796. UniformBuffer.prototype.addVector3 = function (name, vector) {
  35797. var temp = new Array();
  35798. vector.toArray(temp);
  35799. this.addUniform(name, temp);
  35800. };
  35801. /**
  35802. * Wrapper for addUniform.
  35803. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35804. */
  35805. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  35806. this.addUniform(name, 12);
  35807. };
  35808. /**
  35809. * Wrapper for addUniform.
  35810. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35811. */
  35812. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  35813. this.addUniform(name, 8);
  35814. };
  35815. /**
  35816. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  35817. */
  35818. UniformBuffer.prototype.create = function () {
  35819. if (this._noUBO) {
  35820. return;
  35821. }
  35822. if (this._buffer) {
  35823. return; // nothing to do
  35824. }
  35825. // See spec, alignment must be filled as a vec4
  35826. this._fillAlignment(4);
  35827. this._bufferData = new Float32Array(this._data);
  35828. this._rebuild();
  35829. this._needSync = true;
  35830. };
  35831. UniformBuffer.prototype._rebuild = function () {
  35832. if (this._noUBO) {
  35833. return;
  35834. }
  35835. if (this._dynamic) {
  35836. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  35837. }
  35838. else {
  35839. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  35840. }
  35841. };
  35842. /**
  35843. * Updates the WebGL Uniform Buffer on the GPU.
  35844. * If the `dynamic` flag is set to true, no cache comparison is done.
  35845. * Otherwise, the buffer will be updated only if the cache differs.
  35846. */
  35847. UniformBuffer.prototype.update = function () {
  35848. if (!this._buffer) {
  35849. this.create();
  35850. return;
  35851. }
  35852. if (!this._dynamic && !this._needSync) {
  35853. return;
  35854. }
  35855. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  35856. this._needSync = false;
  35857. };
  35858. /**
  35859. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  35860. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  35861. * @param {number[]|Float32Array} data Flattened data
  35862. * @param {number} size Size of the data.
  35863. */
  35864. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  35865. var location = this._uniformLocations[uniformName];
  35866. if (location === undefined) {
  35867. if (this._buffer) {
  35868. // Cannot add an uniform if the buffer is already created
  35869. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  35870. return;
  35871. }
  35872. this.addUniform(uniformName, size);
  35873. location = this._uniformLocations[uniformName];
  35874. }
  35875. if (!this._buffer) {
  35876. this.create();
  35877. }
  35878. if (!this._dynamic) {
  35879. // Cache for static uniform buffers
  35880. var changed = false;
  35881. for (var i = 0; i < size; i++) {
  35882. if (this._bufferData[location + i] !== data[i]) {
  35883. changed = true;
  35884. this._bufferData[location + i] = data[i];
  35885. }
  35886. }
  35887. this._needSync = this._needSync || changed;
  35888. }
  35889. else {
  35890. // No cache for dynamic
  35891. for (var i = 0; i < size; i++) {
  35892. this._bufferData[location + i] = data[i];
  35893. }
  35894. }
  35895. };
  35896. // Update methods
  35897. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  35898. // To match std140, matrix must be realigned
  35899. for (var i = 0; i < 3; i++) {
  35900. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  35901. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  35902. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  35903. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35904. }
  35905. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  35906. };
  35907. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  35908. this._currentEffect.setMatrix3x3(name, matrix);
  35909. };
  35910. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  35911. this._currentEffect.setMatrix2x2(name, matrix);
  35912. };
  35913. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  35914. // To match std140, matrix must be realigned
  35915. for (var i = 0; i < 2; i++) {
  35916. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  35917. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  35918. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  35919. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  35920. }
  35921. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  35922. };
  35923. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  35924. this._currentEffect.setFloat(name, x);
  35925. };
  35926. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  35927. UniformBuffer._tempBuffer[0] = x;
  35928. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  35929. };
  35930. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  35931. if (suffix === void 0) { suffix = ""; }
  35932. this._currentEffect.setFloat2(name + suffix, x, y);
  35933. };
  35934. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  35935. if (suffix === void 0) { suffix = ""; }
  35936. UniformBuffer._tempBuffer[0] = x;
  35937. UniformBuffer._tempBuffer[1] = y;
  35938. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  35939. };
  35940. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  35941. if (suffix === void 0) { suffix = ""; }
  35942. this._currentEffect.setFloat3(name + suffix, x, y, z);
  35943. };
  35944. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  35945. if (suffix === void 0) { suffix = ""; }
  35946. UniformBuffer._tempBuffer[0] = x;
  35947. UniformBuffer._tempBuffer[1] = y;
  35948. UniformBuffer._tempBuffer[2] = z;
  35949. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35950. };
  35951. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  35952. if (suffix === void 0) { suffix = ""; }
  35953. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  35954. };
  35955. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  35956. if (suffix === void 0) { suffix = ""; }
  35957. UniformBuffer._tempBuffer[0] = x;
  35958. UniformBuffer._tempBuffer[1] = y;
  35959. UniformBuffer._tempBuffer[2] = z;
  35960. UniformBuffer._tempBuffer[3] = w;
  35961. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35962. };
  35963. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  35964. this._currentEffect.setMatrix(name, mat);
  35965. };
  35966. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  35967. this.updateUniform(name, mat.toArray(), 16);
  35968. };
  35969. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  35970. this._currentEffect.setVector3(name, vector);
  35971. };
  35972. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  35973. vector.toArray(UniformBuffer._tempBuffer);
  35974. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35975. };
  35976. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  35977. this._currentEffect.setVector4(name, vector);
  35978. };
  35979. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  35980. vector.toArray(UniformBuffer._tempBuffer);
  35981. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  35982. };
  35983. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  35984. if (suffix === void 0) { suffix = ""; }
  35985. this._currentEffect.setColor3(name + suffix, color);
  35986. };
  35987. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  35988. if (suffix === void 0) { suffix = ""; }
  35989. color.toArray(UniformBuffer._tempBuffer);
  35990. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  35991. };
  35992. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  35993. if (suffix === void 0) { suffix = ""; }
  35994. this._currentEffect.setColor4(name + suffix, color, alpha);
  35995. };
  35996. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  35997. if (suffix === void 0) { suffix = ""; }
  35998. color.toArray(UniformBuffer._tempBuffer);
  35999. UniformBuffer._tempBuffer[3] = alpha;
  36000. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36001. };
  36002. /**
  36003. * Sets a sampler uniform on the effect.
  36004. * @param {string} name Name of the sampler.
  36005. * @param {Texture} texture
  36006. */
  36007. UniformBuffer.prototype.setTexture = function (name, texture) {
  36008. this._currentEffect.setTexture(name, texture);
  36009. };
  36010. /**
  36011. * Directly updates the value of the uniform in the cache AND on the GPU.
  36012. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36013. * @param {number[]|Float32Array} data Flattened data
  36014. */
  36015. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  36016. this.updateUniform(uniformName, data, data.length);
  36017. this.update();
  36018. };
  36019. /**
  36020. * Binds this uniform buffer to an effect.
  36021. * @param {Effect} effect
  36022. * @param {string} name Name of the uniform block in the shader.
  36023. */
  36024. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  36025. this._currentEffect = effect;
  36026. if (this._noUBO || !this._buffer) {
  36027. return;
  36028. }
  36029. effect.bindUniformBuffer(this._buffer, name);
  36030. };
  36031. /**
  36032. * Disposes the uniform buffer.
  36033. */
  36034. UniformBuffer.prototype.dispose = function () {
  36035. if (this._noUBO) {
  36036. return;
  36037. }
  36038. var index = this._engine._uniformBuffers.indexOf(this);
  36039. if (index !== -1) {
  36040. this._engine._uniformBuffers.splice(index, 1);
  36041. }
  36042. if (!this._buffer) {
  36043. return;
  36044. }
  36045. if (this._engine._releaseBuffer(this._buffer)) {
  36046. this._buffer = null;
  36047. }
  36048. };
  36049. // Pool for avoiding memory leaks
  36050. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  36051. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  36052. return UniformBuffer;
  36053. }());
  36054. BABYLON.UniformBuffer = UniformBuffer;
  36055. })(BABYLON || (BABYLON = {}));
  36056. //# sourceMappingURL=babylon.uniformBuffer.js.map
  36057. var BABYLON;
  36058. (function (BABYLON) {
  36059. /**
  36060. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  36061. */
  36062. var VertexData = /** @class */ (function () {
  36063. function VertexData() {
  36064. }
  36065. /**
  36066. * Uses the passed data array to set the set the values for the specified kind of data
  36067. * @param data a linear array of floating numbers
  36068. * @param kind the type of data that is being set, eg positions, colors etc
  36069. */
  36070. VertexData.prototype.set = function (data, kind) {
  36071. switch (kind) {
  36072. case BABYLON.VertexBuffer.PositionKind:
  36073. this.positions = data;
  36074. break;
  36075. case BABYLON.VertexBuffer.NormalKind:
  36076. this.normals = data;
  36077. break;
  36078. case BABYLON.VertexBuffer.TangentKind:
  36079. this.tangents = data;
  36080. break;
  36081. case BABYLON.VertexBuffer.UVKind:
  36082. this.uvs = data;
  36083. break;
  36084. case BABYLON.VertexBuffer.UV2Kind:
  36085. this.uvs2 = data;
  36086. break;
  36087. case BABYLON.VertexBuffer.UV3Kind:
  36088. this.uvs3 = data;
  36089. break;
  36090. case BABYLON.VertexBuffer.UV4Kind:
  36091. this.uvs4 = data;
  36092. break;
  36093. case BABYLON.VertexBuffer.UV5Kind:
  36094. this.uvs5 = data;
  36095. break;
  36096. case BABYLON.VertexBuffer.UV6Kind:
  36097. this.uvs6 = data;
  36098. break;
  36099. case BABYLON.VertexBuffer.ColorKind:
  36100. this.colors = data;
  36101. break;
  36102. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36103. this.matricesIndices = data;
  36104. break;
  36105. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36106. this.matricesWeights = data;
  36107. break;
  36108. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36109. this.matricesIndicesExtra = data;
  36110. break;
  36111. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36112. this.matricesWeightsExtra = data;
  36113. break;
  36114. }
  36115. };
  36116. /**
  36117. * Associates the vertexData to the passed Mesh.
  36118. * Sets it as updatable or not (default `false`)
  36119. * @param mesh the mesh the vertexData is applied to
  36120. * @param updatable when used and having the value true allows new data to update the vertexData
  36121. * @returns the VertexData
  36122. */
  36123. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36124. this._applyTo(mesh, updatable);
  36125. return this;
  36126. };
  36127. /**
  36128. * Associates the vertexData to the passed Geometry.
  36129. * Sets it as updatable or not (default `false`)
  36130. * @param geometry the geometry the vertexData is applied to
  36131. * @param updatable when used and having the value true allows new data to update the vertexData
  36132. * @returns VertexData
  36133. */
  36134. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36135. this._applyTo(geometry, updatable);
  36136. return this;
  36137. };
  36138. /**
  36139. * Updates the associated mesh
  36140. * @param mesh the mesh to be updated
  36141. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36142. * @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
  36143. * @returns VertexData
  36144. */
  36145. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36146. this._update(mesh);
  36147. return this;
  36148. };
  36149. /**
  36150. * Updates the associated geometry
  36151. * @param geometry the geometry to be updated
  36152. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36153. * @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
  36154. * @returns VertexData.
  36155. */
  36156. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36157. this._update(geometry);
  36158. return this;
  36159. };
  36160. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36161. if (updatable === void 0) { updatable = false; }
  36162. if (this.positions) {
  36163. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36164. }
  36165. if (this.normals) {
  36166. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36167. }
  36168. if (this.tangents) {
  36169. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36170. }
  36171. if (this.uvs) {
  36172. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36173. }
  36174. if (this.uvs2) {
  36175. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36176. }
  36177. if (this.uvs3) {
  36178. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36179. }
  36180. if (this.uvs4) {
  36181. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36182. }
  36183. if (this.uvs5) {
  36184. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36185. }
  36186. if (this.uvs6) {
  36187. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36188. }
  36189. if (this.colors) {
  36190. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36191. }
  36192. if (this.matricesIndices) {
  36193. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36194. }
  36195. if (this.matricesWeights) {
  36196. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36197. }
  36198. if (this.matricesIndicesExtra) {
  36199. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36200. }
  36201. if (this.matricesWeightsExtra) {
  36202. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36203. }
  36204. if (this.indices) {
  36205. meshOrGeometry.setIndices(this.indices, null, updatable);
  36206. }
  36207. return this;
  36208. };
  36209. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36210. if (this.positions) {
  36211. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36212. }
  36213. if (this.normals) {
  36214. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36215. }
  36216. if (this.tangents) {
  36217. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36218. }
  36219. if (this.uvs) {
  36220. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36221. }
  36222. if (this.uvs2) {
  36223. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36224. }
  36225. if (this.uvs3) {
  36226. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36227. }
  36228. if (this.uvs4) {
  36229. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36230. }
  36231. if (this.uvs5) {
  36232. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36233. }
  36234. if (this.uvs6) {
  36235. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36236. }
  36237. if (this.colors) {
  36238. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36239. }
  36240. if (this.matricesIndices) {
  36241. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36242. }
  36243. if (this.matricesWeights) {
  36244. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36245. }
  36246. if (this.matricesIndicesExtra) {
  36247. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36248. }
  36249. if (this.matricesWeightsExtra) {
  36250. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36251. }
  36252. if (this.indices) {
  36253. meshOrGeometry.setIndices(this.indices, null);
  36254. }
  36255. return this;
  36256. };
  36257. /**
  36258. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36259. * @param matrix the transforming matrix
  36260. * @returns the VertexData
  36261. */
  36262. VertexData.prototype.transform = function (matrix) {
  36263. var transformed = BABYLON.Vector3.Zero();
  36264. var index;
  36265. if (this.positions) {
  36266. var position = BABYLON.Vector3.Zero();
  36267. for (index = 0; index < this.positions.length; index += 3) {
  36268. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36269. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36270. this.positions[index] = transformed.x;
  36271. this.positions[index + 1] = transformed.y;
  36272. this.positions[index + 2] = transformed.z;
  36273. }
  36274. }
  36275. if (this.normals) {
  36276. var normal = BABYLON.Vector3.Zero();
  36277. for (index = 0; index < this.normals.length; index += 3) {
  36278. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36279. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36280. this.normals[index] = transformed.x;
  36281. this.normals[index + 1] = transformed.y;
  36282. this.normals[index + 2] = transformed.z;
  36283. }
  36284. }
  36285. if (this.tangents) {
  36286. var tangent = BABYLON.Vector4.Zero();
  36287. var tangentTransformed = BABYLON.Vector4.Zero();
  36288. for (index = 0; index < this.tangents.length; index += 4) {
  36289. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36290. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36291. this.tangents[index] = tangentTransformed.x;
  36292. this.tangents[index + 1] = tangentTransformed.y;
  36293. this.tangents[index + 2] = tangentTransformed.z;
  36294. this.tangents[index + 3] = tangentTransformed.w;
  36295. }
  36296. }
  36297. return this;
  36298. };
  36299. /**
  36300. * Merges the passed VertexData into the current one
  36301. * @param other the VertexData to be merged into the current one
  36302. * @returns the modified VertexData
  36303. */
  36304. VertexData.prototype.merge = function (other) {
  36305. this._validate();
  36306. other._validate();
  36307. if (!this.normals !== !other.normals ||
  36308. !this.tangents !== !other.tangents ||
  36309. !this.uvs !== !other.uvs ||
  36310. !this.uvs2 !== !other.uvs2 ||
  36311. !this.uvs3 !== !other.uvs3 ||
  36312. !this.uvs4 !== !other.uvs4 ||
  36313. !this.uvs5 !== !other.uvs5 ||
  36314. !this.uvs6 !== !other.uvs6 ||
  36315. !this.colors !== !other.colors ||
  36316. !this.matricesIndices !== !other.matricesIndices ||
  36317. !this.matricesWeights !== !other.matricesWeights ||
  36318. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36319. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36320. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36321. }
  36322. if (other.indices) {
  36323. if (!this.indices) {
  36324. this.indices = [];
  36325. }
  36326. var offset = this.positions ? this.positions.length / 3 : 0;
  36327. for (var index = 0; index < other.indices.length; index++) {
  36328. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  36329. this.indices.push(other.indices[index] + offset);
  36330. }
  36331. }
  36332. this.positions = this._mergeElement(this.positions, other.positions);
  36333. this.normals = this._mergeElement(this.normals, other.normals);
  36334. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36335. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36336. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36337. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36338. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36339. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36340. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36341. this.colors = this._mergeElement(this.colors, other.colors);
  36342. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36343. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36344. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36345. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36346. return this;
  36347. };
  36348. VertexData.prototype._mergeElement = function (source, other) {
  36349. if (!source) {
  36350. return other;
  36351. }
  36352. if (!other) {
  36353. return source;
  36354. }
  36355. var len = other.length + source.length;
  36356. var isSrcTypedArray = source instanceof Float32Array;
  36357. var isOthTypedArray = other instanceof Float32Array;
  36358. // use non-loop method when the source is Float32Array
  36359. if (isSrcTypedArray) {
  36360. var ret32 = new Float32Array(len);
  36361. ret32.set(source);
  36362. ret32.set(other, source.length);
  36363. return ret32;
  36364. // source is number[], when other is also use concat
  36365. }
  36366. else if (!isOthTypedArray) {
  36367. return source.concat(other);
  36368. // source is a number[], but other is a Float32Array, loop required
  36369. }
  36370. else {
  36371. var ret = source.slice(0); // copy source to a separate array
  36372. for (var i = 0, len = other.length; i < len; i++) {
  36373. ret.push(other[i]);
  36374. }
  36375. return ret;
  36376. }
  36377. };
  36378. VertexData.prototype._validate = function () {
  36379. if (!this.positions) {
  36380. throw new Error("Positions are required");
  36381. }
  36382. var getElementCount = function (kind, values) {
  36383. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36384. if ((values.length % stride) !== 0) {
  36385. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36386. }
  36387. return values.length / stride;
  36388. };
  36389. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36390. var validateElementCount = function (kind, values) {
  36391. var elementCount = getElementCount(kind, values);
  36392. if (elementCount !== positionsElementCount) {
  36393. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36394. }
  36395. };
  36396. if (this.normals)
  36397. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36398. if (this.tangents)
  36399. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36400. if (this.uvs)
  36401. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36402. if (this.uvs2)
  36403. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36404. if (this.uvs3)
  36405. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36406. if (this.uvs4)
  36407. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36408. if (this.uvs5)
  36409. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36410. if (this.uvs6)
  36411. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36412. if (this.colors)
  36413. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36414. if (this.matricesIndices)
  36415. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36416. if (this.matricesWeights)
  36417. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36418. if (this.matricesIndicesExtra)
  36419. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36420. if (this.matricesWeightsExtra)
  36421. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36422. };
  36423. /**
  36424. * Serializes the VertexData
  36425. * @returns a serialized object
  36426. */
  36427. VertexData.prototype.serialize = function () {
  36428. var serializationObject = this.serialize();
  36429. if (this.positions) {
  36430. serializationObject.positions = this.positions;
  36431. }
  36432. if (this.normals) {
  36433. serializationObject.normals = this.normals;
  36434. }
  36435. if (this.tangents) {
  36436. serializationObject.tangents = this.tangents;
  36437. }
  36438. if (this.uvs) {
  36439. serializationObject.uvs = this.uvs;
  36440. }
  36441. if (this.uvs2) {
  36442. serializationObject.uvs2 = this.uvs2;
  36443. }
  36444. if (this.uvs3) {
  36445. serializationObject.uvs3 = this.uvs3;
  36446. }
  36447. if (this.uvs4) {
  36448. serializationObject.uvs4 = this.uvs4;
  36449. }
  36450. if (this.uvs5) {
  36451. serializationObject.uvs5 = this.uvs5;
  36452. }
  36453. if (this.uvs6) {
  36454. serializationObject.uvs6 = this.uvs6;
  36455. }
  36456. if (this.colors) {
  36457. serializationObject.colors = this.colors;
  36458. }
  36459. if (this.matricesIndices) {
  36460. serializationObject.matricesIndices = this.matricesIndices;
  36461. serializationObject.matricesIndices._isExpanded = true;
  36462. }
  36463. if (this.matricesWeights) {
  36464. serializationObject.matricesWeights = this.matricesWeights;
  36465. }
  36466. if (this.matricesIndicesExtra) {
  36467. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36468. serializationObject.matricesIndicesExtra._isExpanded = true;
  36469. }
  36470. if (this.matricesWeightsExtra) {
  36471. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36472. }
  36473. serializationObject.indices = this.indices;
  36474. return serializationObject;
  36475. };
  36476. // Statics
  36477. /**
  36478. * Extracts the vertexData from a mesh
  36479. * @param mesh the mesh from which to extract the VertexData
  36480. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36481. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36482. * @returns the object VertexData associated to the passed mesh
  36483. */
  36484. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36485. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36486. };
  36487. /**
  36488. * Extracts the vertexData from the geometry
  36489. * @param geometry the geometry from which to extract the VertexData
  36490. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36491. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36492. * @returns the object VertexData associated to the passed mesh
  36493. */
  36494. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  36495. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  36496. };
  36497. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  36498. var result = new VertexData();
  36499. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36500. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  36501. }
  36502. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36503. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  36504. }
  36505. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36506. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  36507. }
  36508. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36509. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  36510. }
  36511. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36512. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  36513. }
  36514. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36515. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  36516. }
  36517. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36518. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  36519. }
  36520. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36521. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  36522. }
  36523. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36524. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  36525. }
  36526. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36527. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  36528. }
  36529. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36530. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  36531. }
  36532. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36533. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  36534. }
  36535. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  36536. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  36537. }
  36538. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  36539. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  36540. }
  36541. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  36542. return result;
  36543. };
  36544. /**
  36545. * Creates the VertexData for a Ribbon
  36546. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  36547. * * pathArray array of paths, each of which an array of successive Vector3
  36548. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  36549. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  36550. * * 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
  36551. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36552. * * 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)
  36553. * * 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)
  36554. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  36555. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  36556. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  36557. * @returns the VertexData of the ribbon
  36558. */
  36559. VertexData.CreateRibbon = function (options) {
  36560. var pathArray = options.pathArray;
  36561. var closeArray = options.closeArray || false;
  36562. var closePath = options.closePath || false;
  36563. var invertUV = options.invertUV || false;
  36564. var defaultOffset = Math.floor(pathArray[0].length / 2);
  36565. var offset = options.offset || defaultOffset;
  36566. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  36567. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36568. var customUV = options.uvs;
  36569. var customColors = options.colors;
  36570. var positions = [];
  36571. var indices = [];
  36572. var normals = [];
  36573. var uvs = [];
  36574. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  36575. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  36576. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  36577. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  36578. var minlg; // minimal length among all paths from pathArray
  36579. var lg = []; // array of path lengths : nb of vertex per path
  36580. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  36581. var p; // path iterator
  36582. var i; // point iterator
  36583. var j; // point iterator
  36584. // if single path in pathArray
  36585. if (pathArray.length < 2) {
  36586. var ar1 = [];
  36587. var ar2 = [];
  36588. for (i = 0; i < pathArray[0].length - offset; i++) {
  36589. ar1.push(pathArray[0][i]);
  36590. ar2.push(pathArray[0][i + offset]);
  36591. }
  36592. pathArray = [ar1, ar2];
  36593. }
  36594. // positions and horizontal distances (u)
  36595. var idc = 0;
  36596. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  36597. var path;
  36598. var l;
  36599. minlg = pathArray[0].length;
  36600. var vectlg;
  36601. var dist;
  36602. for (p = 0; p < pathArray.length; p++) {
  36603. uTotalDistance[p] = 0;
  36604. us[p] = [0];
  36605. path = pathArray[p];
  36606. l = path.length;
  36607. minlg = (minlg < l) ? minlg : l;
  36608. j = 0;
  36609. while (j < l) {
  36610. positions.push(path[j].x, path[j].y, path[j].z);
  36611. if (j > 0) {
  36612. vectlg = path[j].subtract(path[j - 1]).length();
  36613. dist = vectlg + uTotalDistance[p];
  36614. us[p].push(dist);
  36615. uTotalDistance[p] = dist;
  36616. }
  36617. j++;
  36618. }
  36619. if (closePath) { // an extra hidden vertex is added in the "positions" array
  36620. j--;
  36621. positions.push(path[0].x, path[0].y, path[0].z);
  36622. vectlg = path[j].subtract(path[0]).length();
  36623. dist = vectlg + uTotalDistance[p];
  36624. us[p].push(dist);
  36625. uTotalDistance[p] = dist;
  36626. }
  36627. lg[p] = l + closePathCorr;
  36628. idx[p] = idc;
  36629. idc += (l + closePathCorr);
  36630. }
  36631. // vertical distances (v)
  36632. var path1;
  36633. var path2;
  36634. var vertex1 = null;
  36635. var vertex2 = null;
  36636. for (i = 0; i < minlg + closePathCorr; i++) {
  36637. vTotalDistance[i] = 0;
  36638. vs[i] = [0];
  36639. for (p = 0; p < pathArray.length - 1; p++) {
  36640. path1 = pathArray[p];
  36641. path2 = pathArray[p + 1];
  36642. if (i === minlg) { // closePath
  36643. vertex1 = path1[0];
  36644. vertex2 = path2[0];
  36645. }
  36646. else {
  36647. vertex1 = path1[i];
  36648. vertex2 = path2[i];
  36649. }
  36650. vectlg = vertex2.subtract(vertex1).length();
  36651. dist = vectlg + vTotalDistance[i];
  36652. vs[i].push(dist);
  36653. vTotalDistance[i] = dist;
  36654. }
  36655. if (closeArray && vertex2 && vertex1) {
  36656. path1 = pathArray[p];
  36657. path2 = pathArray[0];
  36658. if (i === minlg) { // closePath
  36659. vertex2 = path2[0];
  36660. }
  36661. vectlg = vertex2.subtract(vertex1).length();
  36662. dist = vectlg + vTotalDistance[i];
  36663. vTotalDistance[i] = dist;
  36664. }
  36665. }
  36666. // uvs
  36667. var u;
  36668. var v;
  36669. if (customUV) {
  36670. for (p = 0; p < customUV.length; p++) {
  36671. uvs.push(customUV[p].x, customUV[p].y);
  36672. }
  36673. }
  36674. else {
  36675. for (p = 0; p < pathArray.length; p++) {
  36676. for (i = 0; i < minlg + closePathCorr; i++) {
  36677. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  36678. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  36679. if (invertUV) {
  36680. uvs.push(v, u);
  36681. }
  36682. else {
  36683. uvs.push(u, v);
  36684. }
  36685. }
  36686. }
  36687. }
  36688. // indices
  36689. p = 0; // path index
  36690. var pi = 0; // positions array index
  36691. var l1 = lg[p] - 1; // path1 length
  36692. var l2 = lg[p + 1] - 1; // path2 length
  36693. var min = (l1 < l2) ? l1 : l2; // current path stop index
  36694. var shft = idx[1] - idx[0]; // shift
  36695. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  36696. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  36697. // 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
  36698. indices.push(pi, pi + shft, pi + 1);
  36699. indices.push(pi + shft + 1, pi + 1, pi + shft);
  36700. pi += 1;
  36701. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  36702. p++;
  36703. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  36704. shft = idx[0] - idx[p];
  36705. l1 = lg[p] - 1;
  36706. l2 = lg[0] - 1;
  36707. }
  36708. else {
  36709. shft = idx[p + 1] - idx[p];
  36710. l1 = lg[p] - 1;
  36711. l2 = lg[p + 1] - 1;
  36712. }
  36713. pi = idx[p];
  36714. min = (l1 < l2) ? l1 + pi : l2 + pi;
  36715. }
  36716. }
  36717. // normals
  36718. VertexData.ComputeNormals(positions, indices, normals);
  36719. if (closePath) { // update both the first and last vertex normals to their average value
  36720. var indexFirst = 0;
  36721. var indexLast = 0;
  36722. for (p = 0; p < pathArray.length; p++) {
  36723. indexFirst = idx[p] * 3;
  36724. if (p + 1 < pathArray.length) {
  36725. indexLast = (idx[p + 1] - 1) * 3;
  36726. }
  36727. else {
  36728. indexLast = normals.length - 3;
  36729. }
  36730. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  36731. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  36732. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  36733. normals[indexLast] = normals[indexFirst];
  36734. normals[indexLast + 1] = normals[indexFirst + 1];
  36735. normals[indexLast + 2] = normals[indexFirst + 2];
  36736. }
  36737. }
  36738. // sides
  36739. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36740. // Colors
  36741. var colors = null;
  36742. if (customColors) {
  36743. colors = new Float32Array(customColors.length * 4);
  36744. for (var c = 0; c < customColors.length; c++) {
  36745. colors[c * 4] = customColors[c].r;
  36746. colors[c * 4 + 1] = customColors[c].g;
  36747. colors[c * 4 + 2] = customColors[c].b;
  36748. colors[c * 4 + 3] = customColors[c].a;
  36749. }
  36750. }
  36751. // Result
  36752. var vertexData = new VertexData();
  36753. var positions32 = new Float32Array(positions);
  36754. var normals32 = new Float32Array(normals);
  36755. var uvs32 = new Float32Array(uvs);
  36756. vertexData.indices = indices;
  36757. vertexData.positions = positions32;
  36758. vertexData.normals = normals32;
  36759. vertexData.uvs = uvs32;
  36760. if (colors) {
  36761. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  36762. }
  36763. if (closePath) {
  36764. vertexData._idx = idx;
  36765. }
  36766. return vertexData;
  36767. };
  36768. /**
  36769. * Creates the VertexData for a box
  36770. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36771. * * size sets the width, height and depth of the box to the value of size, optional default 1
  36772. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  36773. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  36774. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  36775. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  36776. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  36777. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36778. * * 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)
  36779. * * 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)
  36780. * @returns the VertexData of the box
  36781. */
  36782. VertexData.CreateBox = function (options) {
  36783. var normalsSource = [
  36784. new BABYLON.Vector3(0, 0, 1),
  36785. new BABYLON.Vector3(0, 0, -1),
  36786. new BABYLON.Vector3(1, 0, 0),
  36787. new BABYLON.Vector3(-1, 0, 0),
  36788. new BABYLON.Vector3(0, 1, 0),
  36789. new BABYLON.Vector3(0, -1, 0)
  36790. ];
  36791. var indices = [];
  36792. var positions = [];
  36793. var normals = [];
  36794. var uvs = [];
  36795. var width = options.width || options.size || 1;
  36796. var height = options.height || options.size || 1;
  36797. var depth = options.depth || options.size || 1;
  36798. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36799. var faceUV = options.faceUV || new Array(6);
  36800. var faceColors = options.faceColors;
  36801. var colors = [];
  36802. // default face colors and UV if undefined
  36803. for (var f = 0; f < 6; f++) {
  36804. if (faceUV[f] === undefined) {
  36805. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36806. }
  36807. if (faceColors && faceColors[f] === undefined) {
  36808. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36809. }
  36810. }
  36811. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  36812. // Create each face in turn.
  36813. for (var index = 0; index < normalsSource.length; index++) {
  36814. var normal = normalsSource[index];
  36815. // Get two vectors perpendicular to the face normal and to each other.
  36816. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  36817. var side2 = BABYLON.Vector3.Cross(normal, side1);
  36818. // Six indices (two triangles) per face.
  36819. var verticesLength = positions.length / 3;
  36820. indices.push(verticesLength);
  36821. indices.push(verticesLength + 1);
  36822. indices.push(verticesLength + 2);
  36823. indices.push(verticesLength);
  36824. indices.push(verticesLength + 2);
  36825. indices.push(verticesLength + 3);
  36826. // Four vertices per face.
  36827. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  36828. positions.push(vertex.x, vertex.y, vertex.z);
  36829. normals.push(normal.x, normal.y, normal.z);
  36830. uvs.push(faceUV[index].z, faceUV[index].w);
  36831. if (faceColors) {
  36832. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36833. }
  36834. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  36835. positions.push(vertex.x, vertex.y, vertex.z);
  36836. normals.push(normal.x, normal.y, normal.z);
  36837. uvs.push(faceUV[index].x, faceUV[index].w);
  36838. if (faceColors) {
  36839. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36840. }
  36841. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  36842. positions.push(vertex.x, vertex.y, vertex.z);
  36843. normals.push(normal.x, normal.y, normal.z);
  36844. uvs.push(faceUV[index].x, faceUV[index].y);
  36845. if (faceColors) {
  36846. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36847. }
  36848. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  36849. positions.push(vertex.x, vertex.y, vertex.z);
  36850. normals.push(normal.x, normal.y, normal.z);
  36851. uvs.push(faceUV[index].z, faceUV[index].y);
  36852. if (faceColors) {
  36853. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36854. }
  36855. }
  36856. // sides
  36857. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36858. // Result
  36859. var vertexData = new VertexData();
  36860. vertexData.indices = indices;
  36861. vertexData.positions = positions;
  36862. vertexData.normals = normals;
  36863. vertexData.uvs = uvs;
  36864. if (faceColors) {
  36865. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  36866. vertexData.colors = totalColors;
  36867. }
  36868. return vertexData;
  36869. };
  36870. /**
  36871. * Creates the VertexData for an ellipsoid, defaults to a sphere
  36872. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36873. * * segments sets the number of horizontal strips optional, default 32
  36874. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  36875. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  36876. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  36877. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  36878. * * 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
  36879. * * 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
  36880. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36881. * * 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)
  36882. * * 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)
  36883. * @returns the VertexData of the ellipsoid
  36884. */
  36885. VertexData.CreateSphere = function (options) {
  36886. var segments = options.segments || 32;
  36887. var diameterX = options.diameterX || options.diameter || 1;
  36888. var diameterY = options.diameterY || options.diameter || 1;
  36889. var diameterZ = options.diameterZ || options.diameter || 1;
  36890. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36891. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  36892. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36893. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  36894. var totalZRotationSteps = 2 + segments;
  36895. var totalYRotationSteps = 2 * totalZRotationSteps;
  36896. var indices = [];
  36897. var positions = [];
  36898. var normals = [];
  36899. var uvs = [];
  36900. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  36901. var normalizedZ = zRotationStep / totalZRotationSteps;
  36902. var angleZ = normalizedZ * Math.PI * slice;
  36903. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  36904. var normalizedY = yRotationStep / totalYRotationSteps;
  36905. var angleY = normalizedY * Math.PI * 2 * arc;
  36906. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  36907. var rotationY = BABYLON.Matrix.RotationY(angleY);
  36908. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  36909. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  36910. var vertex = complete.multiply(radius);
  36911. var normal = complete.divide(radius).normalize();
  36912. positions.push(vertex.x, vertex.y, vertex.z);
  36913. normals.push(normal.x, normal.y, normal.z);
  36914. uvs.push(normalizedY, normalizedZ);
  36915. }
  36916. if (zRotationStep > 0) {
  36917. var verticesCount = positions.length / 3;
  36918. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  36919. indices.push((firstIndex));
  36920. indices.push((firstIndex + 1));
  36921. indices.push(firstIndex + totalYRotationSteps + 1);
  36922. indices.push((firstIndex + totalYRotationSteps + 1));
  36923. indices.push((firstIndex + 1));
  36924. indices.push((firstIndex + totalYRotationSteps + 2));
  36925. }
  36926. }
  36927. }
  36928. // Sides
  36929. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36930. // Result
  36931. var vertexData = new VertexData();
  36932. vertexData.indices = indices;
  36933. vertexData.positions = positions;
  36934. vertexData.normals = normals;
  36935. vertexData.uvs = uvs;
  36936. return vertexData;
  36937. };
  36938. /**
  36939. * Creates the VertexData for a cylinder, cone or prism
  36940. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36941. * * height sets the height (y direction) of the cylinder, optional, default 2
  36942. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  36943. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  36944. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  36945. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  36946. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  36947. * * 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
  36948. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  36949. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  36950. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  36951. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  36952. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36953. * * 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)
  36954. * * 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)
  36955. * @returns the VertexData of the cylinder, cone or prism
  36956. */
  36957. VertexData.CreateCylinder = function (options) {
  36958. var height = options.height || 2;
  36959. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  36960. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  36961. var tessellation = options.tessellation || 24;
  36962. var subdivisions = options.subdivisions || 1;
  36963. var hasRings = options.hasRings ? true : false;
  36964. var enclose = options.enclose ? true : false;
  36965. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  36966. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36967. var faceUV = options.faceUV || new Array(3);
  36968. var faceColors = options.faceColors;
  36969. // default face colors and UV if undefined
  36970. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  36971. var ringNb = (hasRings) ? subdivisions : 1;
  36972. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  36973. var f;
  36974. for (f = 0; f < surfaceNb; f++) {
  36975. if (faceColors && faceColors[f] === undefined) {
  36976. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36977. }
  36978. }
  36979. for (f = 0; f < surfaceNb; f++) {
  36980. if (faceUV && faceUV[f] === undefined) {
  36981. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36982. }
  36983. }
  36984. var indices = new Array();
  36985. var positions = new Array();
  36986. var normals = new Array();
  36987. var uvs = new Array();
  36988. var colors = new Array();
  36989. var angle_step = Math.PI * 2 * arc / tessellation;
  36990. var angle;
  36991. var h;
  36992. var radius;
  36993. var tan = (diameterBottom - diameterTop) / 2 / height;
  36994. var ringVertex = BABYLON.Vector3.Zero();
  36995. var ringNormal = BABYLON.Vector3.Zero();
  36996. var ringFirstVertex = BABYLON.Vector3.Zero();
  36997. var ringFirstNormal = BABYLON.Vector3.Zero();
  36998. var quadNormal = BABYLON.Vector3.Zero();
  36999. var Y = BABYLON.Axis.Y;
  37000. // positions, normals, uvs
  37001. var i;
  37002. var j;
  37003. var r;
  37004. var ringIdx = 1;
  37005. var s = 1; // surface index
  37006. var cs = 0;
  37007. var v = 0;
  37008. for (i = 0; i <= subdivisions; i++) {
  37009. h = i / subdivisions;
  37010. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  37011. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  37012. for (r = 0; r < ringIdx; r++) {
  37013. if (hasRings) {
  37014. s += r;
  37015. }
  37016. if (enclose) {
  37017. s += 2 * r;
  37018. }
  37019. for (j = 0; j <= tessellation; j++) {
  37020. angle = j * angle_step;
  37021. // position
  37022. ringVertex.x = Math.cos(-angle) * radius;
  37023. ringVertex.y = -height / 2 + h * height;
  37024. ringVertex.z = Math.sin(-angle) * radius;
  37025. // normal
  37026. if (diameterTop === 0 && i === subdivisions) {
  37027. // if no top cap, reuse former normals
  37028. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  37029. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  37030. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  37031. }
  37032. else {
  37033. ringNormal.x = ringVertex.x;
  37034. ringNormal.z = ringVertex.z;
  37035. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  37036. ringNormal.normalize();
  37037. }
  37038. // keep first ring vertex values for enclose
  37039. if (j === 0) {
  37040. ringFirstVertex.copyFrom(ringVertex);
  37041. ringFirstNormal.copyFrom(ringNormal);
  37042. }
  37043. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37044. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  37045. if (hasRings) {
  37046. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  37047. }
  37048. else {
  37049. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37050. }
  37051. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37052. if (faceColors) {
  37053. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37054. }
  37055. }
  37056. // if enclose, add four vertices and their dedicated normals
  37057. if (arc !== 1 && enclose) {
  37058. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37059. positions.push(0, ringVertex.y, 0);
  37060. positions.push(0, ringVertex.y, 0);
  37061. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37062. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37063. quadNormal.normalize();
  37064. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37065. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37066. quadNormal.normalize();
  37067. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37068. if (hasRings) {
  37069. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37070. }
  37071. else {
  37072. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37073. }
  37074. uvs.push(faceUV[s + 1].x, v);
  37075. uvs.push(faceUV[s + 1].z, v);
  37076. if (hasRings) {
  37077. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37078. }
  37079. else {
  37080. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37081. }
  37082. uvs.push(faceUV[s + 2].x, v);
  37083. uvs.push(faceUV[s + 2].z, v);
  37084. if (faceColors) {
  37085. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37086. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37087. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37088. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37089. }
  37090. }
  37091. if (cs !== s) {
  37092. cs = s;
  37093. }
  37094. }
  37095. }
  37096. // indices
  37097. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37098. var s;
  37099. i = 0;
  37100. for (s = 0; s < subdivisions; s++) {
  37101. var i0 = 0;
  37102. var i1 = 0;
  37103. var i2 = 0;
  37104. var i3 = 0;
  37105. for (j = 0; j < tessellation; j++) {
  37106. i0 = i * (e + 1) + j;
  37107. i1 = (i + 1) * (e + 1) + j;
  37108. i2 = i * (e + 1) + (j + 1);
  37109. i3 = (i + 1) * (e + 1) + (j + 1);
  37110. indices.push(i0, i1, i2);
  37111. indices.push(i3, i2, i1);
  37112. }
  37113. if (arc !== 1 && enclose) { // if enclose, add two quads
  37114. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37115. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37116. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37117. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37118. }
  37119. i = (hasRings) ? (i + 2) : (i + 1);
  37120. }
  37121. // Caps
  37122. var createCylinderCap = function (isTop) {
  37123. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37124. if (radius === 0) {
  37125. return;
  37126. }
  37127. // Cap positions, normals & uvs
  37128. var angle;
  37129. var circleVector;
  37130. var i;
  37131. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37132. var c = null;
  37133. if (faceColors) {
  37134. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37135. }
  37136. // cap center
  37137. var vbase = positions.length / 3;
  37138. var offset = isTop ? height / 2 : -height / 2;
  37139. var center = new BABYLON.Vector3(0, offset, 0);
  37140. positions.push(center.x, center.y, center.z);
  37141. normals.push(0, isTop ? 1 : -1, 0);
  37142. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37143. if (c) {
  37144. colors.push(c.r, c.g, c.b, c.a);
  37145. }
  37146. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37147. for (i = 0; i <= tessellation; i++) {
  37148. angle = Math.PI * 2 * i * arc / tessellation;
  37149. var cos = Math.cos(-angle);
  37150. var sin = Math.sin(-angle);
  37151. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37152. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37153. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37154. normals.push(0, isTop ? 1 : -1, 0);
  37155. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37156. if (c) {
  37157. colors.push(c.r, c.g, c.b, c.a);
  37158. }
  37159. }
  37160. // Cap indices
  37161. for (i = 0; i < tessellation; i++) {
  37162. if (!isTop) {
  37163. indices.push(vbase);
  37164. indices.push(vbase + (i + 1));
  37165. indices.push(vbase + (i + 2));
  37166. }
  37167. else {
  37168. indices.push(vbase);
  37169. indices.push(vbase + (i + 2));
  37170. indices.push(vbase + (i + 1));
  37171. }
  37172. }
  37173. };
  37174. // add caps to geometry
  37175. createCylinderCap(false);
  37176. createCylinderCap(true);
  37177. // Sides
  37178. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37179. var vertexData = new VertexData();
  37180. vertexData.indices = indices;
  37181. vertexData.positions = positions;
  37182. vertexData.normals = normals;
  37183. vertexData.uvs = uvs;
  37184. if (faceColors) {
  37185. vertexData.colors = colors;
  37186. }
  37187. return vertexData;
  37188. };
  37189. /**
  37190. * Creates the VertexData for a torus
  37191. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37192. * * diameter the diameter of the torus, optional default 1
  37193. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37194. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37195. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37196. * * 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)
  37197. * * 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)
  37198. * @returns the VertexData of the torus
  37199. */
  37200. VertexData.CreateTorus = function (options) {
  37201. var indices = [];
  37202. var positions = [];
  37203. var normals = [];
  37204. var uvs = [];
  37205. var diameter = options.diameter || 1;
  37206. var thickness = options.thickness || 0.5;
  37207. var tessellation = options.tessellation || 16;
  37208. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37209. var stride = tessellation + 1;
  37210. for (var i = 0; i <= tessellation; i++) {
  37211. var u = i / tessellation;
  37212. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37213. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37214. for (var j = 0; j <= tessellation; j++) {
  37215. var v = 1 - j / tessellation;
  37216. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37217. var dx = Math.cos(innerAngle);
  37218. var dy = Math.sin(innerAngle);
  37219. // Create a vertex.
  37220. var normal = new BABYLON.Vector3(dx, dy, 0);
  37221. var position = normal.scale(thickness / 2);
  37222. var textureCoordinate = new BABYLON.Vector2(u, v);
  37223. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37224. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37225. positions.push(position.x, position.y, position.z);
  37226. normals.push(normal.x, normal.y, normal.z);
  37227. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37228. // And create indices for two triangles.
  37229. var nextI = (i + 1) % stride;
  37230. var nextJ = (j + 1) % stride;
  37231. indices.push(i * stride + j);
  37232. indices.push(i * stride + nextJ);
  37233. indices.push(nextI * stride + j);
  37234. indices.push(i * stride + nextJ);
  37235. indices.push(nextI * stride + nextJ);
  37236. indices.push(nextI * stride + j);
  37237. }
  37238. }
  37239. // Sides
  37240. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37241. // Result
  37242. var vertexData = new VertexData();
  37243. vertexData.indices = indices;
  37244. vertexData.positions = positions;
  37245. vertexData.normals = normals;
  37246. vertexData.uvs = uvs;
  37247. return vertexData;
  37248. };
  37249. /**
  37250. * Creates the VertexData of the LineSystem
  37251. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37252. * - lines an array of lines, each line being an array of successive Vector3
  37253. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37254. * @returns the VertexData of the LineSystem
  37255. */
  37256. VertexData.CreateLineSystem = function (options) {
  37257. var indices = [];
  37258. var positions = [];
  37259. var lines = options.lines;
  37260. var colors = options.colors;
  37261. var vertexColors = [];
  37262. var idx = 0;
  37263. for (var l = 0; l < lines.length; l++) {
  37264. var points = lines[l];
  37265. for (var index = 0; index < points.length; index++) {
  37266. positions.push(points[index].x, points[index].y, points[index].z);
  37267. if (colors) {
  37268. var color = colors[l];
  37269. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37270. }
  37271. if (index > 0) {
  37272. indices.push(idx - 1);
  37273. indices.push(idx);
  37274. }
  37275. idx++;
  37276. }
  37277. }
  37278. var vertexData = new VertexData();
  37279. vertexData.indices = indices;
  37280. vertexData.positions = positions;
  37281. if (colors) {
  37282. vertexData.colors = vertexColors;
  37283. }
  37284. return vertexData;
  37285. };
  37286. /**
  37287. * Create the VertexData for a DashedLines
  37288. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37289. * - points an array successive Vector3
  37290. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37291. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37292. * - dashNb the intended total number of dashes, optional, default 200
  37293. * @returns the VertexData for the DashedLines
  37294. */
  37295. VertexData.CreateDashedLines = function (options) {
  37296. var dashSize = options.dashSize || 3;
  37297. var gapSize = options.gapSize || 1;
  37298. var dashNb = options.dashNb || 200;
  37299. var points = options.points;
  37300. var positions = new Array();
  37301. var indices = new Array();
  37302. var curvect = BABYLON.Vector3.Zero();
  37303. var lg = 0;
  37304. var nb = 0;
  37305. var shft = 0;
  37306. var dashshft = 0;
  37307. var curshft = 0;
  37308. var idx = 0;
  37309. var i = 0;
  37310. for (i = 0; i < points.length - 1; i++) {
  37311. points[i + 1].subtractToRef(points[i], curvect);
  37312. lg += curvect.length();
  37313. }
  37314. shft = lg / dashNb;
  37315. dashshft = dashSize * shft / (dashSize + gapSize);
  37316. for (i = 0; i < points.length - 1; i++) {
  37317. points[i + 1].subtractToRef(points[i], curvect);
  37318. nb = Math.floor(curvect.length() / shft);
  37319. curvect.normalize();
  37320. for (var j = 0; j < nb; j++) {
  37321. curshft = shft * j;
  37322. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37323. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37324. indices.push(idx, idx + 1);
  37325. idx += 2;
  37326. }
  37327. }
  37328. // Result
  37329. var vertexData = new VertexData();
  37330. vertexData.positions = positions;
  37331. vertexData.indices = indices;
  37332. return vertexData;
  37333. };
  37334. /**
  37335. * Creates the VertexData for a Ground
  37336. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37337. * - width the width (x direction) of the ground, optional, default 1
  37338. * - height the height (z direction) of the ground, optional, default 1
  37339. * - subdivisions the number of subdivisions per side, optional, default 1
  37340. * @returns the VertexData of the Ground
  37341. */
  37342. VertexData.CreateGround = function (options) {
  37343. var indices = [];
  37344. var positions = [];
  37345. var normals = [];
  37346. var uvs = [];
  37347. var row, col;
  37348. var width = options.width || 1;
  37349. var height = options.height || 1;
  37350. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37351. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37352. for (row = 0; row <= subdivisionsY; row++) {
  37353. for (col = 0; col <= subdivisionsX; col++) {
  37354. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37355. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37356. positions.push(position.x, position.y, position.z);
  37357. normals.push(normal.x, normal.y, normal.z);
  37358. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37359. }
  37360. }
  37361. for (row = 0; row < subdivisionsY; row++) {
  37362. for (col = 0; col < subdivisionsX; col++) {
  37363. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37364. indices.push(col + 1 + row * (subdivisionsX + 1));
  37365. indices.push(col + row * (subdivisionsX + 1));
  37366. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37367. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37368. indices.push(col + row * (subdivisionsX + 1));
  37369. }
  37370. }
  37371. // Result
  37372. var vertexData = new VertexData();
  37373. vertexData.indices = indices;
  37374. vertexData.positions = positions;
  37375. vertexData.normals = normals;
  37376. vertexData.uvs = uvs;
  37377. return vertexData;
  37378. };
  37379. /**
  37380. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37381. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37382. * * xmin the ground minimum X coordinate, optional, default -1
  37383. * * zmin the ground minimum Z coordinate, optional, default -1
  37384. * * xmax the ground maximum X coordinate, optional, default 1
  37385. * * zmax the ground maximum Z coordinate, optional, default 1
  37386. * * 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}
  37387. * * 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}
  37388. * @returns the VertexData of the TiledGround
  37389. */
  37390. VertexData.CreateTiledGround = function (options) {
  37391. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37392. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37393. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37394. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37395. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37396. var precision = options.precision || { w: 1, h: 1 };
  37397. var indices = new Array();
  37398. var positions = new Array();
  37399. var normals = new Array();
  37400. var uvs = new Array();
  37401. var row, col, tileRow, tileCol;
  37402. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37403. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37404. precision.w = (precision.w < 1) ? 1 : precision.w;
  37405. precision.h = (precision.h < 1) ? 1 : precision.h;
  37406. var tileSize = {
  37407. 'w': (xmax - xmin) / subdivisions.w,
  37408. 'h': (zmax - zmin) / subdivisions.h
  37409. };
  37410. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37411. // Indices
  37412. var base = positions.length / 3;
  37413. var rowLength = precision.w + 1;
  37414. for (row = 0; row < precision.h; row++) {
  37415. for (col = 0; col < precision.w; col++) {
  37416. var square = [
  37417. base + col + row * rowLength,
  37418. base + (col + 1) + row * rowLength,
  37419. base + (col + 1) + (row + 1) * rowLength,
  37420. base + col + (row + 1) * rowLength
  37421. ];
  37422. indices.push(square[1]);
  37423. indices.push(square[2]);
  37424. indices.push(square[3]);
  37425. indices.push(square[0]);
  37426. indices.push(square[1]);
  37427. indices.push(square[3]);
  37428. }
  37429. }
  37430. // Position, normals and uvs
  37431. var position = BABYLON.Vector3.Zero();
  37432. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37433. for (row = 0; row <= precision.h; row++) {
  37434. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37435. for (col = 0; col <= precision.w; col++) {
  37436. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37437. position.y = 0;
  37438. positions.push(position.x, position.y, position.z);
  37439. normals.push(normal.x, normal.y, normal.z);
  37440. uvs.push(col / precision.w, row / precision.h);
  37441. }
  37442. }
  37443. }
  37444. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37445. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37446. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37447. }
  37448. }
  37449. // Result
  37450. var vertexData = new VertexData();
  37451. vertexData.indices = indices;
  37452. vertexData.positions = positions;
  37453. vertexData.normals = normals;
  37454. vertexData.uvs = uvs;
  37455. return vertexData;
  37456. };
  37457. /**
  37458. * Creates the VertexData of the Ground designed from a heightmap
  37459. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37460. * * width the width (x direction) of the ground
  37461. * * height the height (z direction) of the ground
  37462. * * subdivisions the number of subdivisions per side
  37463. * * minHeight the minimum altitude on the ground, optional, default 0
  37464. * * maxHeight the maximum altitude on the ground, optional default 1
  37465. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37466. * * buffer the array holding the image color data
  37467. * * bufferWidth the width of image
  37468. * * bufferHeight the height of image
  37469. * @returns the VertexData of the Ground designed from a heightmap
  37470. */
  37471. VertexData.CreateGroundFromHeightMap = function (options) {
  37472. var indices = [];
  37473. var positions = [];
  37474. var normals = [];
  37475. var uvs = [];
  37476. var row, col;
  37477. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37478. // Vertices
  37479. for (row = 0; row <= options.subdivisions; row++) {
  37480. for (col = 0; col <= options.subdivisions; col++) {
  37481. 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));
  37482. // Compute height
  37483. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37484. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37485. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37486. var r = options.buffer[pos] / 255.0;
  37487. var g = options.buffer[pos + 1] / 255.0;
  37488. var b = options.buffer[pos + 2] / 255.0;
  37489. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37490. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37491. // Add vertex
  37492. positions.push(position.x, position.y, position.z);
  37493. normals.push(0, 0, 0);
  37494. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37495. }
  37496. }
  37497. // Indices
  37498. for (row = 0; row < options.subdivisions; row++) {
  37499. for (col = 0; col < options.subdivisions; col++) {
  37500. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37501. indices.push(col + 1 + row * (options.subdivisions + 1));
  37502. indices.push(col + row * (options.subdivisions + 1));
  37503. indices.push(col + (row + 1) * (options.subdivisions + 1));
  37504. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37505. indices.push(col + row * (options.subdivisions + 1));
  37506. }
  37507. }
  37508. // Normals
  37509. VertexData.ComputeNormals(positions, indices, normals);
  37510. // Result
  37511. var vertexData = new VertexData();
  37512. vertexData.indices = indices;
  37513. vertexData.positions = positions;
  37514. vertexData.normals = normals;
  37515. vertexData.uvs = uvs;
  37516. return vertexData;
  37517. };
  37518. /**
  37519. * Creates the VertexData for a Plane
  37520. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  37521. * * size sets the width and height of the plane to the value of size, optional default 1
  37522. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  37523. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  37524. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37525. * * 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)
  37526. * * 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)
  37527. * @returns the VertexData of the box
  37528. */
  37529. VertexData.CreatePlane = function (options) {
  37530. var indices = [];
  37531. var positions = [];
  37532. var normals = [];
  37533. var uvs = [];
  37534. var width = options.width || options.size || 1;
  37535. var height = options.height || options.size || 1;
  37536. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37537. // Vertices
  37538. var halfWidth = width / 2.0;
  37539. var halfHeight = height / 2.0;
  37540. positions.push(-halfWidth, -halfHeight, 0);
  37541. normals.push(0, 0, -1.0);
  37542. uvs.push(0.0, 0.0);
  37543. positions.push(halfWidth, -halfHeight, 0);
  37544. normals.push(0, 0, -1.0);
  37545. uvs.push(1.0, 0.0);
  37546. positions.push(halfWidth, halfHeight, 0);
  37547. normals.push(0, 0, -1.0);
  37548. uvs.push(1.0, 1.0);
  37549. positions.push(-halfWidth, halfHeight, 0);
  37550. normals.push(0, 0, -1.0);
  37551. uvs.push(0.0, 1.0);
  37552. // Indices
  37553. indices.push(0);
  37554. indices.push(1);
  37555. indices.push(2);
  37556. indices.push(0);
  37557. indices.push(2);
  37558. indices.push(3);
  37559. // Sides
  37560. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37561. // Result
  37562. var vertexData = new VertexData();
  37563. vertexData.indices = indices;
  37564. vertexData.positions = positions;
  37565. vertexData.normals = normals;
  37566. vertexData.uvs = uvs;
  37567. return vertexData;
  37568. };
  37569. /**
  37570. * Creates the VertexData of the Disc or regular Polygon
  37571. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  37572. * * radius the radius of the disc, optional default 0.5
  37573. * * tessellation the number of polygon sides, optional, default 64
  37574. * * 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
  37575. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37576. * * 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)
  37577. * * 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)
  37578. * @returns the VertexData of the box
  37579. */
  37580. VertexData.CreateDisc = function (options) {
  37581. var positions = new Array();
  37582. var indices = new Array();
  37583. var normals = new Array();
  37584. var uvs = new Array();
  37585. var radius = options.radius || 0.5;
  37586. var tessellation = options.tessellation || 64;
  37587. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37588. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37589. // positions and uvs
  37590. positions.push(0, 0, 0); // disc center first
  37591. uvs.push(0.5, 0.5);
  37592. var theta = Math.PI * 2 * arc;
  37593. var step = theta / tessellation;
  37594. for (var a = 0; a < theta; a += step) {
  37595. var x = Math.cos(a);
  37596. var y = Math.sin(a);
  37597. var u = (x + 1) / 2;
  37598. var v = (1 - y) / 2;
  37599. positions.push(radius * x, radius * y, 0);
  37600. uvs.push(u, v);
  37601. }
  37602. if (arc === 1) {
  37603. positions.push(positions[3], positions[4], positions[5]); // close the circle
  37604. uvs.push(uvs[2], uvs[3]);
  37605. }
  37606. //indices
  37607. var vertexNb = positions.length / 3;
  37608. for (var i = 1; i < vertexNb - 1; i++) {
  37609. indices.push(i + 1, 0, i);
  37610. }
  37611. // result
  37612. VertexData.ComputeNormals(positions, indices, normals);
  37613. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37614. var vertexData = new VertexData();
  37615. vertexData.indices = indices;
  37616. vertexData.positions = positions;
  37617. vertexData.normals = normals;
  37618. vertexData.uvs = uvs;
  37619. return vertexData;
  37620. };
  37621. /**
  37622. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  37623. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  37624. * @param polygon a mesh built from polygonTriangulation.build()
  37625. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37626. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37627. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37628. * @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)
  37629. * @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)
  37630. * @returns the VertexData of the Polygon
  37631. */
  37632. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  37633. var faceUV = fUV || new Array(3);
  37634. var faceColors = fColors;
  37635. var colors = [];
  37636. // default face colors and UV if undefined
  37637. for (var f = 0; f < 3; f++) {
  37638. if (faceUV[f] === undefined) {
  37639. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37640. }
  37641. if (faceColors && faceColors[f] === undefined) {
  37642. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37643. }
  37644. }
  37645. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37646. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37647. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37648. var indices = polygon.getIndices();
  37649. // set face colours and textures
  37650. var idx = 0;
  37651. var face = 0;
  37652. for (var index = 0; index < normals.length; index += 3) {
  37653. //Edge Face no. 1
  37654. if (Math.abs(normals[index + 1]) < 0.001) {
  37655. face = 1;
  37656. }
  37657. //Top Face no. 0
  37658. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  37659. face = 0;
  37660. }
  37661. //Bottom Face no. 2
  37662. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  37663. face = 2;
  37664. }
  37665. idx = index / 3;
  37666. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  37667. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  37668. if (faceColors) {
  37669. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  37670. }
  37671. }
  37672. // sides
  37673. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  37674. // Result
  37675. var vertexData = new VertexData();
  37676. vertexData.indices = indices;
  37677. vertexData.positions = positions;
  37678. vertexData.normals = normals;
  37679. vertexData.uvs = uvs;
  37680. if (faceColors) {
  37681. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37682. vertexData.colors = totalColors;
  37683. }
  37684. return vertexData;
  37685. };
  37686. /**
  37687. * Creates the VertexData of the IcoSphere
  37688. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  37689. * * radius the radius of the IcoSphere, optional default 1
  37690. * * radiusX allows stretching in the x direction, optional, default radius
  37691. * * radiusY allows stretching in the y direction, optional, default radius
  37692. * * radiusZ allows stretching in the z direction, optional, default radius
  37693. * * flat when true creates a flat shaded mesh, optional, default true
  37694. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37695. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37696. * * 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)
  37697. * * 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)
  37698. * @returns the VertexData of the IcoSphere
  37699. */
  37700. VertexData.CreateIcoSphere = function (options) {
  37701. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37702. var radius = options.radius || 1;
  37703. var flat = (options.flat === undefined) ? true : options.flat;
  37704. var subdivisions = options.subdivisions || 4;
  37705. var radiusX = options.radiusX || radius;
  37706. var radiusY = options.radiusY || radius;
  37707. var radiusZ = options.radiusZ || radius;
  37708. var t = (1 + Math.sqrt(5)) / 2;
  37709. // 12 vertex x,y,z
  37710. var ico_vertices = [
  37711. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  37712. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  37713. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  37714. ];
  37715. // index of 3 vertex makes a face of icopshere
  37716. var ico_indices = [
  37717. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  37718. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  37719. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  37720. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  37721. ];
  37722. // vertex for uv have aliased position, not for UV
  37723. var vertices_unalias_id = [
  37724. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  37725. // vertex alias
  37726. 0,
  37727. 2,
  37728. 3,
  37729. 3,
  37730. 3,
  37731. 4,
  37732. 7,
  37733. 8,
  37734. 9,
  37735. 9,
  37736. 10,
  37737. 11 // 23: B + 12
  37738. ];
  37739. // uv as integer step (not pixels !)
  37740. var ico_vertexuv = [
  37741. 5, 1, 3, 1, 6, 4, 0, 0,
  37742. 5, 3, 4, 2, 2, 2, 4, 0,
  37743. 2, 0, 1, 1, 6, 0, 6, 2,
  37744. // vertex alias (for same vertex on different faces)
  37745. 0, 4,
  37746. 3, 3,
  37747. 4, 4,
  37748. 3, 1,
  37749. 4, 2,
  37750. 4, 4,
  37751. 0, 2,
  37752. 1, 1,
  37753. 2, 2,
  37754. 3, 3,
  37755. 1, 3,
  37756. 2, 4 // 23: B + 12
  37757. ];
  37758. // Vertices[0, 1, ...9, A, B] : position on UV plane
  37759. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  37760. // First island of uv mapping
  37761. // v = 4h 3+ 2
  37762. // v = 3h 9+ 4
  37763. // v = 2h 9+ 5 B
  37764. // v = 1h 9 1 0
  37765. // v = 0h 3 8 7 A
  37766. // u = 0 1 2 3 4 5 6 *a
  37767. // Second island of uv mapping
  37768. // v = 4h 0+ B+ 4+
  37769. // v = 3h A+ 2+
  37770. // v = 2h 7+ 6 3+
  37771. // v = 1h 8+ 3+
  37772. // v = 0h
  37773. // u = 0 1 2 3 4 5 6 *a
  37774. // Face layout on texture UV mapping
  37775. // ============
  37776. // \ 4 /\ 16 / ======
  37777. // \ / \ / /\ 11 /
  37778. // \/ 7 \/ / \ /
  37779. // ======= / 10 \/
  37780. // /\ 17 /\ =======
  37781. // / \ / \ \ 15 /\
  37782. // / 8 \/ 12 \ \ / \
  37783. // ============ \/ 6 \
  37784. // \ 18 /\ ============
  37785. // \ / \ \ 5 /\ 0 /
  37786. // \/ 13 \ \ / \ /
  37787. // ======= \/ 1 \/
  37788. // =============
  37789. // /\ 19 /\ 2 /\
  37790. // / \ / \ / \
  37791. // / 14 \/ 9 \/ 3 \
  37792. // ===================
  37793. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  37794. var ustep = 138 / 1024;
  37795. var vstep = 239 / 1024;
  37796. var uoffset = 60 / 1024;
  37797. var voffset = 26 / 1024;
  37798. // Second island should have margin, not to touch the first island
  37799. // avoid any borderline artefact in pixel rounding
  37800. var island_u_offset = -40 / 1024;
  37801. var island_v_offset = +20 / 1024;
  37802. // face is either island 0 or 1 :
  37803. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  37804. var island = [
  37805. 0, 0, 0, 0, 1,
  37806. 0, 0, 1, 1, 0,
  37807. 0, 0, 1, 1, 0,
  37808. 0, 1, 1, 1, 0 // 15 - 19
  37809. ];
  37810. var indices = new Array();
  37811. var positions = new Array();
  37812. var normals = new Array();
  37813. var uvs = new Array();
  37814. var current_indice = 0;
  37815. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  37816. var face_vertex_pos = new Array(3);
  37817. var face_vertex_uv = new Array(3);
  37818. var v012;
  37819. for (v012 = 0; v012 < 3; v012++) {
  37820. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  37821. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  37822. }
  37823. // create all with normals
  37824. for (var face = 0; face < 20; face++) {
  37825. // 3 vertex per face
  37826. for (v012 = 0; v012 < 3; v012++) {
  37827. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  37828. var v_id = ico_indices[3 * face + v012];
  37829. // vertex have 3D position (x,y,z)
  37830. 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]);
  37831. // Normalize to get normal, then scale to radius
  37832. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  37833. // uv Coordinates from vertex ID
  37834. 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);
  37835. }
  37836. // Subdivide the face (interpolate pos, norm, uv)
  37837. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  37838. // - norm is linear interpolation of vertex corner normal
  37839. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  37840. // - uv is linear interpolation
  37841. //
  37842. // Topology is as below for sub-divide by 2
  37843. // vertex shown as v0,v1,v2
  37844. // interp index is i1 to progress in range [v0,v1[
  37845. // interp index is i2 to progress in range [v0,v2[
  37846. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  37847. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37848. //
  37849. //
  37850. // i2 v2
  37851. // ^ ^
  37852. // / / \
  37853. // / / \
  37854. // / / \
  37855. // / / (0,1) \
  37856. // / #---------\
  37857. // / / \ (0,0)'/ \
  37858. // / / \ / \
  37859. // / / \ / \
  37860. // / / (0,0) \ / (1,0) \
  37861. // / #---------#---------\
  37862. // v0 v1
  37863. //
  37864. // --------------------> i1
  37865. //
  37866. // interp of (i1,i2):
  37867. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  37868. // along i1 : lerp(x0,x1, i1/(S-i2))
  37869. //
  37870. // centroid of triangle is needed to get help normal computation
  37871. // (c1,c2) are used for centroid location
  37872. var interp_vertex = function (i1, i2, c1, c2) {
  37873. // vertex is interpolated from
  37874. // - face_vertex_pos[0..2]
  37875. // - face_vertex_uv[0..2]
  37876. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  37877. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  37878. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  37879. pos_interp.normalize();
  37880. var vertex_normal;
  37881. if (flat) {
  37882. // in flat mode, recalculate normal as face centroid normal
  37883. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  37884. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  37885. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  37886. }
  37887. else {
  37888. // in smooth mode, recalculate normal from each single vertex position
  37889. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  37890. }
  37891. // Vertex normal need correction due to X,Y,Z radius scaling
  37892. vertex_normal.x /= radiusX;
  37893. vertex_normal.y /= radiusY;
  37894. vertex_normal.z /= radiusZ;
  37895. vertex_normal.normalize();
  37896. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  37897. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  37898. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  37899. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  37900. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  37901. uvs.push(uv_interp.x, uv_interp.y);
  37902. // push each vertex has member of a face
  37903. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  37904. indices.push(current_indice);
  37905. current_indice++;
  37906. };
  37907. for (var i2 = 0; i2 < subdivisions; i2++) {
  37908. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  37909. // face : (i1,i2) for /\ :
  37910. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  37911. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37912. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37913. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  37914. if (i1 + i2 + 1 < subdivisions) {
  37915. // face : (i1,i2)' for \/ :
  37916. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37917. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37918. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37919. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  37920. }
  37921. }
  37922. }
  37923. }
  37924. // Sides
  37925. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  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. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  37935. /**
  37936. * Creates the VertexData for a Polyhedron
  37937. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  37938. * * type provided types are:
  37939. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  37940. * * 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)
  37941. * * size the size of the IcoSphere, optional default 1
  37942. * * sizeX allows stretching in the x direction, optional, default size
  37943. * * sizeY allows stretching in the y direction, optional, default size
  37944. * * sizeZ allows stretching in the z direction, optional, default size
  37945. * * 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
  37946. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37947. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37948. * * flat when true creates a flat shaded mesh, optional, default true
  37949. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37950. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37951. * * 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)
  37952. * * 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)
  37953. * @returns the VertexData of the Polyhedron
  37954. */
  37955. VertexData.CreatePolyhedron = function (options) {
  37956. // provided polyhedron types :
  37957. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  37958. // 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)
  37959. var polyhedra = [];
  37960. 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]] };
  37961. 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]] };
  37962. polyhedra[2] = {
  37963. 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]],
  37964. 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]]
  37965. };
  37966. polyhedra[3] = {
  37967. 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]],
  37968. 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]]
  37969. };
  37970. polyhedra[4] = {
  37971. 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]],
  37972. 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]]
  37973. };
  37974. 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]] };
  37975. 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]] };
  37976. 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]] };
  37977. 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]] };
  37978. 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]] };
  37979. 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]] };
  37980. 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]] };
  37981. 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]] };
  37982. 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]] };
  37983. polyhedra[14] = {
  37984. 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]],
  37985. 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]]
  37986. };
  37987. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  37988. var size = options.size;
  37989. var sizeX = options.sizeX || size || 1;
  37990. var sizeY = options.sizeY || size || 1;
  37991. var sizeZ = options.sizeZ || size || 1;
  37992. var data = options.custom || polyhedra[type];
  37993. var nbfaces = data.face.length;
  37994. var faceUV = options.faceUV || new Array(nbfaces);
  37995. var faceColors = options.faceColors;
  37996. var flat = (options.flat === undefined) ? true : options.flat;
  37997. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37998. var positions = new Array();
  37999. var indices = new Array();
  38000. var normals = new Array();
  38001. var uvs = new Array();
  38002. var colors = new Array();
  38003. var index = 0;
  38004. var faceIdx = 0; // face cursor in the array "indexes"
  38005. var indexes = new Array();
  38006. var i = 0;
  38007. var f = 0;
  38008. var u, v, ang, x, y, tmp;
  38009. // default face colors and UV if undefined
  38010. if (flat) {
  38011. for (f = 0; f < nbfaces; f++) {
  38012. if (faceColors && faceColors[f] === undefined) {
  38013. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38014. }
  38015. if (faceUV && faceUV[f] === undefined) {
  38016. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38017. }
  38018. }
  38019. }
  38020. if (!flat) {
  38021. for (i = 0; i < data.vertex.length; i++) {
  38022. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  38023. uvs.push(0, 0);
  38024. }
  38025. for (f = 0; f < nbfaces; f++) {
  38026. for (i = 0; i < data.face[f].length - 2; i++) {
  38027. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  38028. }
  38029. }
  38030. }
  38031. else {
  38032. for (f = 0; f < nbfaces; f++) {
  38033. var fl = data.face[f].length; // number of vertices of the current face
  38034. ang = 2 * Math.PI / fl;
  38035. x = 0.5 * Math.tan(ang / 2);
  38036. y = 0.5;
  38037. // positions, uvs, colors
  38038. for (i = 0; i < fl; i++) {
  38039. // positions
  38040. 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);
  38041. indexes.push(index);
  38042. index++;
  38043. // uvs
  38044. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  38045. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  38046. uvs.push(u, v);
  38047. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  38048. y = x * Math.sin(ang) + y * Math.cos(ang);
  38049. x = tmp;
  38050. // colors
  38051. if (faceColors) {
  38052. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38053. }
  38054. }
  38055. // indices from indexes
  38056. for (i = 0; i < fl - 2; i++) {
  38057. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38058. }
  38059. faceIdx += fl;
  38060. }
  38061. }
  38062. VertexData.ComputeNormals(positions, indices, normals);
  38063. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38064. var vertexData = new VertexData();
  38065. vertexData.positions = positions;
  38066. vertexData.indices = indices;
  38067. vertexData.normals = normals;
  38068. vertexData.uvs = uvs;
  38069. if (faceColors && flat) {
  38070. vertexData.colors = colors;
  38071. }
  38072. return vertexData;
  38073. };
  38074. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38075. /**
  38076. * Creates the VertexData for a TorusKnot
  38077. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  38078. * * radius the radius of the torus knot, optional, default 2
  38079. * * tube the thickness of the tube, optional, default 0.5
  38080. * * radialSegments the number of sides on each tube segments, optional, default 32
  38081. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  38082. * * p the number of windings around the z axis, optional, default 2
  38083. * * q the number of windings around the x axis, optional, default 3
  38084. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38085. * * 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)
  38086. * * 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)
  38087. * @returns the VertexData of the Torus Knot
  38088. */
  38089. VertexData.CreateTorusKnot = function (options) {
  38090. var indices = new Array();
  38091. var positions = new Array();
  38092. var normals = new Array();
  38093. var uvs = new Array();
  38094. var radius = options.radius || 2;
  38095. var tube = options.tube || 0.5;
  38096. var radialSegments = options.radialSegments || 32;
  38097. var tubularSegments = options.tubularSegments || 32;
  38098. var p = options.p || 2;
  38099. var q = options.q || 3;
  38100. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38101. // Helper
  38102. var getPos = function (angle) {
  38103. var cu = Math.cos(angle);
  38104. var su = Math.sin(angle);
  38105. var quOverP = q / p * angle;
  38106. var cs = Math.cos(quOverP);
  38107. var tx = radius * (2 + cs) * 0.5 * cu;
  38108. var ty = radius * (2 + cs) * su * 0.5;
  38109. var tz = radius * Math.sin(quOverP) * 0.5;
  38110. return new BABYLON.Vector3(tx, ty, tz);
  38111. };
  38112. // Vertices
  38113. var i;
  38114. var j;
  38115. for (i = 0; i <= radialSegments; i++) {
  38116. var modI = i % radialSegments;
  38117. var u = modI / radialSegments * 2 * p * Math.PI;
  38118. var p1 = getPos(u);
  38119. var p2 = getPos(u + 0.01);
  38120. var tang = p2.subtract(p1);
  38121. var n = p2.add(p1);
  38122. var bitan = BABYLON.Vector3.Cross(tang, n);
  38123. n = BABYLON.Vector3.Cross(bitan, tang);
  38124. bitan.normalize();
  38125. n.normalize();
  38126. for (j = 0; j < tubularSegments; j++) {
  38127. var modJ = j % tubularSegments;
  38128. var v = modJ / tubularSegments * 2 * Math.PI;
  38129. var cx = -tube * Math.cos(v);
  38130. var cy = tube * Math.sin(v);
  38131. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38132. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38133. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38134. uvs.push(i / radialSegments);
  38135. uvs.push(j / tubularSegments);
  38136. }
  38137. }
  38138. for (i = 0; i < radialSegments; i++) {
  38139. for (j = 0; j < tubularSegments; j++) {
  38140. var jNext = (j + 1) % tubularSegments;
  38141. var a = i * tubularSegments + j;
  38142. var b = (i + 1) * tubularSegments + j;
  38143. var c = (i + 1) * tubularSegments + jNext;
  38144. var d = i * tubularSegments + jNext;
  38145. indices.push(d);
  38146. indices.push(b);
  38147. indices.push(a);
  38148. indices.push(d);
  38149. indices.push(c);
  38150. indices.push(b);
  38151. }
  38152. }
  38153. // Normals
  38154. VertexData.ComputeNormals(positions, indices, normals);
  38155. // Sides
  38156. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38157. // Result
  38158. var vertexData = new VertexData();
  38159. vertexData.indices = indices;
  38160. vertexData.positions = positions;
  38161. vertexData.normals = normals;
  38162. vertexData.uvs = uvs;
  38163. return vertexData;
  38164. };
  38165. // Tools
  38166. /**
  38167. * Compute normals for given positions and indices
  38168. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38169. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38170. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38171. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38172. * * facetNormals : optional array of facet normals (vector3)
  38173. * * facetPositions : optional array of facet positions (vector3)
  38174. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38175. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38176. * * bInfo : optional bounding info, required for facetPartitioning computation
  38177. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38178. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38179. * * useRightHandedSystem: optional boolean to for right handed system computation
  38180. * * depthSort : optional boolean to enable the facet depth sort computation
  38181. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38182. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38183. */
  38184. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38185. // temporary scalar variables
  38186. var index = 0; // facet index
  38187. var p1p2x = 0.0; // p1p2 vector x coordinate
  38188. var p1p2y = 0.0; // p1p2 vector y coordinate
  38189. var p1p2z = 0.0; // p1p2 vector z coordinate
  38190. var p3p2x = 0.0; // p3p2 vector x coordinate
  38191. var p3p2y = 0.0; // p3p2 vector y coordinate
  38192. var p3p2z = 0.0; // p3p2 vector z coordinate
  38193. var faceNormalx = 0.0; // facet normal x coordinate
  38194. var faceNormaly = 0.0; // facet normal y coordinate
  38195. var faceNormalz = 0.0; // facet normal z coordinate
  38196. var length = 0.0; // facet normal length before normalization
  38197. var v1x = 0; // vector1 x index in the positions array
  38198. var v1y = 0; // vector1 y index in the positions array
  38199. var v1z = 0; // vector1 z index in the positions array
  38200. var v2x = 0; // vector2 x index in the positions array
  38201. var v2y = 0; // vector2 y index in the positions array
  38202. var v2z = 0; // vector2 z index in the positions array
  38203. var v3x = 0; // vector3 x index in the positions array
  38204. var v3y = 0; // vector3 y index in the positions array
  38205. var v3z = 0; // vector3 z index in the positions array
  38206. var computeFacetNormals = false;
  38207. var computeFacetPositions = false;
  38208. var computeFacetPartitioning = false;
  38209. var computeDepthSort = false;
  38210. var faceNormalSign = 1;
  38211. var ratio = 0;
  38212. var distanceTo = null;
  38213. if (options) {
  38214. computeFacetNormals = (options.facetNormals) ? true : false;
  38215. computeFacetPositions = (options.facetPositions) ? true : false;
  38216. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38217. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38218. ratio = options.ratio || 0;
  38219. computeDepthSort = (options.depthSort) ? true : false;
  38220. distanceTo = (options.distanceTo);
  38221. if (computeDepthSort) {
  38222. if (distanceTo === undefined) {
  38223. distanceTo = BABYLON.Vector3.Zero();
  38224. }
  38225. var depthSortedFacets = options.depthSortedFacets;
  38226. }
  38227. }
  38228. // facetPartitioning reinit if needed
  38229. var xSubRatio = 0;
  38230. var ySubRatio = 0;
  38231. var zSubRatio = 0;
  38232. var subSq = 0;
  38233. if (computeFacetPartitioning && options && options.bbSize) {
  38234. var ox = 0; // X partitioning index for facet position
  38235. var oy = 0; // Y partinioning index for facet position
  38236. var oz = 0; // Z partinioning index for facet position
  38237. var b1x = 0; // X partitioning index for facet v1 vertex
  38238. var b1y = 0; // Y partitioning index for facet v1 vertex
  38239. var b1z = 0; // z partitioning index for facet v1 vertex
  38240. var b2x = 0; // X partitioning index for facet v2 vertex
  38241. var b2y = 0; // Y partitioning index for facet v2 vertex
  38242. var b2z = 0; // Z partitioning index for facet v2 vertex
  38243. var b3x = 0; // X partitioning index for facet v3 vertex
  38244. var b3y = 0; // Y partitioning index for facet v3 vertex
  38245. var b3z = 0; // Z partitioning index for facet v3 vertex
  38246. var block_idx_o = 0; // facet barycenter block index
  38247. var block_idx_v1 = 0; // v1 vertex block index
  38248. var block_idx_v2 = 0; // v2 vertex block index
  38249. var block_idx_v3 = 0; // v3 vertex block index
  38250. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38251. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38252. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38253. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38254. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38255. subSq = options.subDiv.max * options.subDiv.max;
  38256. options.facetPartitioning.length = 0;
  38257. }
  38258. // reset the normals
  38259. for (index = 0; index < positions.length; index++) {
  38260. normals[index] = 0.0;
  38261. }
  38262. // Loop : 1 indice triplet = 1 facet
  38263. var nbFaces = (indices.length / 3) | 0;
  38264. for (index = 0; index < nbFaces; index++) {
  38265. // get the indexes of the coordinates of each vertex of the facet
  38266. v1x = indices[index * 3] * 3;
  38267. v1y = v1x + 1;
  38268. v1z = v1x + 2;
  38269. v2x = indices[index * 3 + 1] * 3;
  38270. v2y = v2x + 1;
  38271. v2z = v2x + 2;
  38272. v3x = indices[index * 3 + 2] * 3;
  38273. v3y = v3x + 1;
  38274. v3z = v3x + 2;
  38275. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38276. p1p2y = positions[v1y] - positions[v2y];
  38277. p1p2z = positions[v1z] - positions[v2z];
  38278. p3p2x = positions[v3x] - positions[v2x];
  38279. p3p2y = positions[v3y] - positions[v2y];
  38280. p3p2z = positions[v3z] - positions[v2z];
  38281. // compute the face normal with the cross product
  38282. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38283. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38284. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38285. // normalize this normal and store it in the array facetData
  38286. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38287. length = (length === 0) ? 1.0 : length;
  38288. faceNormalx /= length;
  38289. faceNormaly /= length;
  38290. faceNormalz /= length;
  38291. if (computeFacetNormals && options) {
  38292. options.facetNormals[index].x = faceNormalx;
  38293. options.facetNormals[index].y = faceNormaly;
  38294. options.facetNormals[index].z = faceNormalz;
  38295. }
  38296. if (computeFacetPositions && options) {
  38297. // compute and the facet barycenter coordinates in the array facetPositions
  38298. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38299. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38300. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38301. }
  38302. if (computeFacetPartitioning && options) {
  38303. // store the facet indexes in arrays in the main facetPartitioning array :
  38304. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38305. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38306. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38307. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38308. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38309. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38310. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38311. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38312. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38313. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38314. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38315. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38316. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38317. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38318. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38319. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38320. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38321. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38322. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38323. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38324. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38325. // push each facet index in each block containing the vertex
  38326. options.facetPartitioning[block_idx_v1].push(index);
  38327. if (block_idx_v2 != block_idx_v1) {
  38328. options.facetPartitioning[block_idx_v2].push(index);
  38329. }
  38330. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38331. options.facetPartitioning[block_idx_v3].push(index);
  38332. }
  38333. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38334. options.facetPartitioning[block_idx_o].push(index);
  38335. }
  38336. }
  38337. if (computeDepthSort && options && options.facetPositions) {
  38338. var dsf = depthSortedFacets[index];
  38339. dsf.ind = index * 3;
  38340. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38341. }
  38342. // compute the normals anyway
  38343. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38344. normals[v1y] += faceNormaly;
  38345. normals[v1z] += faceNormalz;
  38346. normals[v2x] += faceNormalx;
  38347. normals[v2y] += faceNormaly;
  38348. normals[v2z] += faceNormalz;
  38349. normals[v3x] += faceNormalx;
  38350. normals[v3y] += faceNormaly;
  38351. normals[v3z] += faceNormalz;
  38352. }
  38353. // last normalization of each normal
  38354. for (index = 0; index < normals.length / 3; index++) {
  38355. faceNormalx = normals[index * 3];
  38356. faceNormaly = normals[index * 3 + 1];
  38357. faceNormalz = normals[index * 3 + 2];
  38358. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38359. length = (length === 0) ? 1.0 : length;
  38360. faceNormalx /= length;
  38361. faceNormaly /= length;
  38362. faceNormalz /= length;
  38363. normals[index * 3] = faceNormalx;
  38364. normals[index * 3 + 1] = faceNormaly;
  38365. normals[index * 3 + 2] = faceNormalz;
  38366. }
  38367. };
  38368. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38369. var li = indices.length;
  38370. var ln = normals.length;
  38371. var i;
  38372. var n;
  38373. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38374. switch (sideOrientation) {
  38375. case BABYLON.Mesh.FRONTSIDE:
  38376. // nothing changed
  38377. break;
  38378. case BABYLON.Mesh.BACKSIDE:
  38379. var tmp;
  38380. // indices
  38381. for (i = 0; i < li; i += 3) {
  38382. tmp = indices[i];
  38383. indices[i] = indices[i + 2];
  38384. indices[i + 2] = tmp;
  38385. }
  38386. // normals
  38387. for (n = 0; n < ln; n++) {
  38388. normals[n] = -normals[n];
  38389. }
  38390. break;
  38391. case BABYLON.Mesh.DOUBLESIDE:
  38392. // positions
  38393. var lp = positions.length;
  38394. var l = lp / 3;
  38395. for (var p = 0; p < lp; p++) {
  38396. positions[lp + p] = positions[p];
  38397. }
  38398. // indices
  38399. for (i = 0; i < li; i += 3) {
  38400. indices[i + li] = indices[i + 2] + l;
  38401. indices[i + 1 + li] = indices[i + 1] + l;
  38402. indices[i + 2 + li] = indices[i] + l;
  38403. }
  38404. // normals
  38405. for (n = 0; n < ln; n++) {
  38406. normals[ln + n] = -normals[n];
  38407. }
  38408. // uvs
  38409. var lu = uvs.length;
  38410. var u = 0;
  38411. for (u = 0; u < lu; u++) {
  38412. uvs[u + lu] = uvs[u];
  38413. }
  38414. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38415. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38416. u = 0;
  38417. for (i = 0; i < lu / 2; i++) {
  38418. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38419. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38420. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38421. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38422. u += 2;
  38423. }
  38424. break;
  38425. }
  38426. };
  38427. /**
  38428. * Applies VertexData created from the imported parameters to the geometry
  38429. * @param parsedVertexData the parsed data from an imported file
  38430. * @param geometry the geometry to apply the VertexData to
  38431. */
  38432. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38433. var vertexData = new VertexData();
  38434. // positions
  38435. var positions = parsedVertexData.positions;
  38436. if (positions) {
  38437. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38438. }
  38439. // normals
  38440. var normals = parsedVertexData.normals;
  38441. if (normals) {
  38442. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38443. }
  38444. // tangents
  38445. var tangents = parsedVertexData.tangents;
  38446. if (tangents) {
  38447. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38448. }
  38449. // uvs
  38450. var uvs = parsedVertexData.uvs;
  38451. if (uvs) {
  38452. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38453. }
  38454. // uv2s
  38455. var uv2s = parsedVertexData.uv2s;
  38456. if (uv2s) {
  38457. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38458. }
  38459. // uv3s
  38460. var uv3s = parsedVertexData.uv3s;
  38461. if (uv3s) {
  38462. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38463. }
  38464. // uv4s
  38465. var uv4s = parsedVertexData.uv4s;
  38466. if (uv4s) {
  38467. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38468. }
  38469. // uv5s
  38470. var uv5s = parsedVertexData.uv5s;
  38471. if (uv5s) {
  38472. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38473. }
  38474. // uv6s
  38475. var uv6s = parsedVertexData.uv6s;
  38476. if (uv6s) {
  38477. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38478. }
  38479. // colors
  38480. var colors = parsedVertexData.colors;
  38481. if (colors) {
  38482. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38483. }
  38484. // matricesIndices
  38485. var matricesIndices = parsedVertexData.matricesIndices;
  38486. if (matricesIndices) {
  38487. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38488. }
  38489. // matricesWeights
  38490. var matricesWeights = parsedVertexData.matricesWeights;
  38491. if (matricesWeights) {
  38492. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38493. }
  38494. // indices
  38495. var indices = parsedVertexData.indices;
  38496. if (indices) {
  38497. vertexData.indices = indices;
  38498. }
  38499. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38500. };
  38501. return VertexData;
  38502. }());
  38503. BABYLON.VertexData = VertexData;
  38504. })(BABYLON || (BABYLON = {}));
  38505. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38506. var BABYLON;
  38507. (function (BABYLON) {
  38508. /**
  38509. * Class used to store geometry data (vertex buffers + index buffer)
  38510. */
  38511. var Geometry = /** @class */ (function () {
  38512. /**
  38513. * Creates a new geometry
  38514. * @param id defines the unique ID
  38515. * @param scene defines the hosting scene
  38516. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  38517. * @param updatable defines if geometry must be updatable (false by default)
  38518. * @param mesh defines the mesh that will be associated with the geometry
  38519. */
  38520. function Geometry(id, scene, vertexData, updatable, mesh) {
  38521. if (updatable === void 0) { updatable = false; }
  38522. if (mesh === void 0) { mesh = null; }
  38523. /**
  38524. * Gets the delay loading state of the geometry (none by default which means not delayed)
  38525. */
  38526. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38527. this._totalVertices = 0;
  38528. this._isDisposed = false;
  38529. this._indexBufferIsUpdatable = false;
  38530. this.id = id;
  38531. this._engine = scene.getEngine();
  38532. this._meshes = [];
  38533. this._scene = scene;
  38534. //Init vertex buffer cache
  38535. this._vertexBuffers = {};
  38536. this._indices = [];
  38537. this._updatable = updatable;
  38538. // vertexData
  38539. if (vertexData) {
  38540. this.setAllVerticesData(vertexData, updatable);
  38541. }
  38542. else {
  38543. this._totalVertices = 0;
  38544. this._indices = [];
  38545. }
  38546. if (this._engine.getCaps().vertexArrayObject) {
  38547. this._vertexArrayObjects = {};
  38548. }
  38549. // applyToMesh
  38550. if (mesh) {
  38551. if (mesh.getClassName() === "LinesMesh") {
  38552. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  38553. this._updateExtend();
  38554. }
  38555. this.applyToMesh(mesh);
  38556. mesh.computeWorldMatrix(true);
  38557. }
  38558. }
  38559. Object.defineProperty(Geometry.prototype, "boundingBias", {
  38560. /**
  38561. * 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
  38562. */
  38563. get: function () {
  38564. return this._boundingBias;
  38565. },
  38566. /**
  38567. * 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
  38568. */
  38569. set: function (value) {
  38570. if (this._boundingBias && this._boundingBias.equals(value)) {
  38571. return;
  38572. }
  38573. this._boundingBias = value.clone();
  38574. this._updateBoundingInfo(true, null);
  38575. },
  38576. enumerable: true,
  38577. configurable: true
  38578. });
  38579. /**
  38580. * Static function used to attach a new empty geometry to a mesh
  38581. * @param mesh defines the mesh to attach the geometry to
  38582. * @returns the new {BABYLON.Geometry}
  38583. */
  38584. Geometry.CreateGeometryForMesh = function (mesh) {
  38585. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  38586. geometry.applyToMesh(mesh);
  38587. return geometry;
  38588. };
  38589. Object.defineProperty(Geometry.prototype, "extend", {
  38590. /**
  38591. * Gets the current extend of the geometry
  38592. */
  38593. get: function () {
  38594. return this._extend;
  38595. },
  38596. enumerable: true,
  38597. configurable: true
  38598. });
  38599. /**
  38600. * Gets the hosting scene
  38601. * @returns the hosting {BABYLON.Scene}
  38602. */
  38603. Geometry.prototype.getScene = function () {
  38604. return this._scene;
  38605. };
  38606. /**
  38607. * Gets the hosting engine
  38608. * @returns the hosting {BABYLON.Engine}
  38609. */
  38610. Geometry.prototype.getEngine = function () {
  38611. return this._engine;
  38612. };
  38613. /**
  38614. * Defines if the geometry is ready to use
  38615. * @returns true if the geometry is ready to be used
  38616. */
  38617. Geometry.prototype.isReady = function () {
  38618. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  38619. };
  38620. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  38621. /**
  38622. * Gets a value indicating that the geometry should not be serialized
  38623. */
  38624. get: function () {
  38625. for (var index = 0; index < this._meshes.length; index++) {
  38626. if (!this._meshes[index].doNotSerialize) {
  38627. return false;
  38628. }
  38629. }
  38630. return true;
  38631. },
  38632. enumerable: true,
  38633. configurable: true
  38634. });
  38635. /** @hidden */
  38636. Geometry.prototype._rebuild = function () {
  38637. if (this._vertexArrayObjects) {
  38638. this._vertexArrayObjects = {};
  38639. }
  38640. // Index buffer
  38641. if (this._meshes.length !== 0 && this._indices) {
  38642. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38643. }
  38644. // Vertex buffers
  38645. for (var key in this._vertexBuffers) {
  38646. var vertexBuffer = this._vertexBuffers[key];
  38647. vertexBuffer._rebuild();
  38648. }
  38649. };
  38650. /**
  38651. * Affects all gemetry data in one call
  38652. * @param vertexData defines the geometry data
  38653. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  38654. */
  38655. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  38656. vertexData.applyToGeometry(this, updatable);
  38657. this.notifyUpdate();
  38658. };
  38659. /**
  38660. * Set specific vertex data
  38661. * @param kind defines the data kind (Position, normal, etc...)
  38662. * @param data defines the vertex data to use
  38663. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  38664. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  38665. */
  38666. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  38667. if (updatable === void 0) { updatable = false; }
  38668. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  38669. this.setVerticesBuffer(buffer);
  38670. };
  38671. /**
  38672. * Removes a specific vertex data
  38673. * @param kind defines the data kind (Position, normal, etc...)
  38674. */
  38675. Geometry.prototype.removeVerticesData = function (kind) {
  38676. if (this._vertexBuffers[kind]) {
  38677. this._vertexBuffers[kind].dispose();
  38678. delete this._vertexBuffers[kind];
  38679. }
  38680. };
  38681. /**
  38682. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  38683. * @param buffer defines the vertex buffer to use
  38684. * @param totalVertices defines the total number of vertices for position kind (could be null)
  38685. */
  38686. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  38687. if (totalVertices === void 0) { totalVertices = null; }
  38688. var kind = buffer.getKind();
  38689. if (this._vertexBuffers[kind]) {
  38690. this._vertexBuffers[kind].dispose();
  38691. }
  38692. this._vertexBuffers[kind] = buffer;
  38693. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38694. var data = buffer.getData();
  38695. if (totalVertices != null) {
  38696. this._totalVertices = totalVertices;
  38697. }
  38698. else {
  38699. if (data != null) {
  38700. this._totalVertices = data.length / (buffer.byteStride / 4);
  38701. }
  38702. }
  38703. this._updateExtend(data);
  38704. this._resetPointsArrayCache();
  38705. var meshes = this._meshes;
  38706. var numOfMeshes = meshes.length;
  38707. for (var index = 0; index < numOfMeshes; index++) {
  38708. var mesh = meshes[index];
  38709. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38710. mesh._createGlobalSubMesh(false);
  38711. mesh.computeWorldMatrix(true);
  38712. }
  38713. }
  38714. this.notifyUpdate(kind);
  38715. if (this._vertexArrayObjects) {
  38716. this._disposeVertexArrayObjects();
  38717. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  38718. }
  38719. };
  38720. /**
  38721. * Update a specific vertex buffer
  38722. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  38723. * It will do nothing if the buffer is not updatable
  38724. * @param kind defines the data kind (Position, normal, etc...)
  38725. * @param data defines the data to use
  38726. * @param offset defines the offset in the target buffer where to store the data
  38727. * @param useBytes set to true if the offset is in bytes
  38728. */
  38729. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  38730. if (useBytes === void 0) { useBytes = false; }
  38731. var vertexBuffer = this.getVertexBuffer(kind);
  38732. if (!vertexBuffer) {
  38733. return;
  38734. }
  38735. vertexBuffer.updateDirectly(data, offset, useBytes);
  38736. this.notifyUpdate(kind);
  38737. };
  38738. /**
  38739. * Update a specific vertex buffer
  38740. * This function will create a new buffer if the current one is not updatable
  38741. * @param kind defines the data kind (Position, normal, etc...)
  38742. * @param data defines the data to use
  38743. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  38744. */
  38745. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  38746. if (updateExtends === void 0) { updateExtends = false; }
  38747. var vertexBuffer = this.getVertexBuffer(kind);
  38748. if (!vertexBuffer) {
  38749. return;
  38750. }
  38751. vertexBuffer.update(data);
  38752. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38753. this._updateBoundingInfo(updateExtends, data);
  38754. }
  38755. this.notifyUpdate(kind);
  38756. };
  38757. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  38758. if (updateExtends) {
  38759. this._updateExtend(data);
  38760. }
  38761. var meshes = this._meshes;
  38762. var numOfMeshes = meshes.length;
  38763. this._resetPointsArrayCache();
  38764. for (var index = 0; index < numOfMeshes; index++) {
  38765. var mesh = meshes[index];
  38766. if (updateExtends) {
  38767. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38768. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  38769. var subMesh = mesh.subMeshes[subIndex];
  38770. subMesh.refreshBoundingInfo();
  38771. }
  38772. }
  38773. }
  38774. };
  38775. /** @hidden */
  38776. Geometry.prototype._bind = function (effect, indexToBind) {
  38777. if (!effect) {
  38778. return;
  38779. }
  38780. if (indexToBind === undefined) {
  38781. indexToBind = this._indexBuffer;
  38782. }
  38783. var vbs = this.getVertexBuffers();
  38784. if (!vbs) {
  38785. return;
  38786. }
  38787. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  38788. this._engine.bindBuffers(vbs, indexToBind, effect);
  38789. return;
  38790. }
  38791. // Using VAO
  38792. if (!this._vertexArrayObjects[effect.key]) {
  38793. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  38794. }
  38795. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  38796. };
  38797. /**
  38798. * Gets total number of vertices
  38799. * @returns the total number of vertices
  38800. */
  38801. Geometry.prototype.getTotalVertices = function () {
  38802. if (!this.isReady()) {
  38803. return 0;
  38804. }
  38805. return this._totalVertices;
  38806. };
  38807. /**
  38808. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  38809. * @param kind defines the data kind (Position, normal, etc...)
  38810. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38811. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  38812. * @returns a float array containing vertex data
  38813. */
  38814. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  38815. var vertexBuffer = this.getVertexBuffer(kind);
  38816. if (!vertexBuffer) {
  38817. return null;
  38818. }
  38819. var data = vertexBuffer.getData();
  38820. if (!data) {
  38821. return null;
  38822. }
  38823. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  38824. var count = this._totalVertices * vertexBuffer.getSize();
  38825. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  38826. var copy_1 = new Array(count);
  38827. vertexBuffer.forEach(count, function (value, index) {
  38828. copy_1[index] = value;
  38829. });
  38830. return copy_1;
  38831. }
  38832. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  38833. if (data instanceof Array) {
  38834. var offset = vertexBuffer.byteOffset / 4;
  38835. return BABYLON.Tools.Slice(data, offset, offset + count);
  38836. }
  38837. else if (data instanceof ArrayBuffer) {
  38838. return new Float32Array(data, vertexBuffer.byteOffset, count);
  38839. }
  38840. else {
  38841. return new Float32Array(data.buffer, data.byteOffset + vertexBuffer.byteOffset, count);
  38842. }
  38843. }
  38844. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  38845. return BABYLON.Tools.Slice(data);
  38846. }
  38847. return data;
  38848. };
  38849. /**
  38850. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  38851. * @param kind defines the data kind (Position, normal, etc...)
  38852. * @returns true if the vertex buffer with the specified kind is updatable
  38853. */
  38854. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  38855. var vb = this._vertexBuffers[kind];
  38856. if (!vb) {
  38857. return false;
  38858. }
  38859. return vb.isUpdatable();
  38860. };
  38861. /**
  38862. * Gets a specific vertex buffer
  38863. * @param kind defines the data kind (Position, normal, etc...)
  38864. * @returns a {BABYLON.VertexBuffer}
  38865. */
  38866. Geometry.prototype.getVertexBuffer = function (kind) {
  38867. if (!this.isReady()) {
  38868. return null;
  38869. }
  38870. return this._vertexBuffers[kind];
  38871. };
  38872. /**
  38873. * Returns all vertex buffers
  38874. * @return an object holding all vertex buffers indexed by kind
  38875. */
  38876. Geometry.prototype.getVertexBuffers = function () {
  38877. if (!this.isReady()) {
  38878. return null;
  38879. }
  38880. return this._vertexBuffers;
  38881. };
  38882. /**
  38883. * Gets a boolean indicating if specific vertex buffer is present
  38884. * @param kind defines the data kind (Position, normal, etc...)
  38885. * @returns true if data is present
  38886. */
  38887. Geometry.prototype.isVerticesDataPresent = function (kind) {
  38888. if (!this._vertexBuffers) {
  38889. if (this._delayInfo) {
  38890. return this._delayInfo.indexOf(kind) !== -1;
  38891. }
  38892. return false;
  38893. }
  38894. return this._vertexBuffers[kind] !== undefined;
  38895. };
  38896. /**
  38897. * Gets a list of all attached data kinds (Position, normal, etc...)
  38898. * @returns a list of string containing all kinds
  38899. */
  38900. Geometry.prototype.getVerticesDataKinds = function () {
  38901. var result = [];
  38902. var kind;
  38903. if (!this._vertexBuffers && this._delayInfo) {
  38904. for (kind in this._delayInfo) {
  38905. result.push(kind);
  38906. }
  38907. }
  38908. else {
  38909. for (kind in this._vertexBuffers) {
  38910. result.push(kind);
  38911. }
  38912. }
  38913. return result;
  38914. };
  38915. /**
  38916. * Update index buffer
  38917. * @param indices defines the indices to store in the index buffer
  38918. * @param offset defines the offset in the target buffer where to store the data
  38919. */
  38920. Geometry.prototype.updateIndices = function (indices, offset) {
  38921. if (!this._indexBuffer) {
  38922. return;
  38923. }
  38924. if (!this._indexBufferIsUpdatable) {
  38925. this.setIndices(indices, null, true);
  38926. }
  38927. else {
  38928. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  38929. }
  38930. };
  38931. /**
  38932. * Creates a new index buffer
  38933. * @param indices defines the indices to store in the index buffer
  38934. * @param totalVertices defines the total number of vertices (could be null)
  38935. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  38936. */
  38937. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  38938. if (totalVertices === void 0) { totalVertices = null; }
  38939. if (updatable === void 0) { updatable = false; }
  38940. if (this._indexBuffer) {
  38941. this._engine._releaseBuffer(this._indexBuffer);
  38942. }
  38943. this._disposeVertexArrayObjects();
  38944. this._indices = indices;
  38945. this._indexBufferIsUpdatable = updatable;
  38946. if (this._meshes.length !== 0 && this._indices) {
  38947. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  38948. }
  38949. if (totalVertices != undefined) { // including null and undefined
  38950. this._totalVertices = totalVertices;
  38951. }
  38952. var meshes = this._meshes;
  38953. var numOfMeshes = meshes.length;
  38954. for (var index = 0; index < numOfMeshes; index++) {
  38955. meshes[index]._createGlobalSubMesh(true);
  38956. }
  38957. this.notifyUpdate();
  38958. };
  38959. /**
  38960. * Return the total number of indices
  38961. * @returns the total number of indices
  38962. */
  38963. Geometry.prototype.getTotalIndices = function () {
  38964. if (!this.isReady()) {
  38965. return 0;
  38966. }
  38967. return this._indices.length;
  38968. };
  38969. /**
  38970. * Gets the index buffer array
  38971. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38972. * @returns the index buffer array
  38973. */
  38974. Geometry.prototype.getIndices = function (copyWhenShared) {
  38975. if (!this.isReady()) {
  38976. return null;
  38977. }
  38978. var orig = this._indices;
  38979. if (!copyWhenShared || this._meshes.length === 1) {
  38980. return orig;
  38981. }
  38982. else {
  38983. var len = orig.length;
  38984. var copy = [];
  38985. for (var i = 0; i < len; i++) {
  38986. copy.push(orig[i]);
  38987. }
  38988. return copy;
  38989. }
  38990. };
  38991. /**
  38992. * Gets the index buffer
  38993. * @return the index buffer
  38994. */
  38995. Geometry.prototype.getIndexBuffer = function () {
  38996. if (!this.isReady()) {
  38997. return null;
  38998. }
  38999. return this._indexBuffer;
  39000. };
  39001. /** @hidden */
  39002. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  39003. if (effect === void 0) { effect = null; }
  39004. if (!effect || !this._vertexArrayObjects) {
  39005. return;
  39006. }
  39007. if (this._vertexArrayObjects[effect.key]) {
  39008. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  39009. delete this._vertexArrayObjects[effect.key];
  39010. }
  39011. };
  39012. /**
  39013. * Release the associated resources for a specific mesh
  39014. * @param mesh defines the source mesh
  39015. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  39016. */
  39017. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  39018. var meshes = this._meshes;
  39019. var index = meshes.indexOf(mesh);
  39020. if (index === -1) {
  39021. return;
  39022. }
  39023. meshes.splice(index, 1);
  39024. mesh._geometry = null;
  39025. if (meshes.length === 0 && shouldDispose) {
  39026. this.dispose();
  39027. }
  39028. };
  39029. /**
  39030. * Apply current geometry to a given mesh
  39031. * @param mesh defines the mesh to apply geometry to
  39032. */
  39033. Geometry.prototype.applyToMesh = function (mesh) {
  39034. if (mesh._geometry === this) {
  39035. return;
  39036. }
  39037. var previousGeometry = mesh._geometry;
  39038. if (previousGeometry) {
  39039. previousGeometry.releaseForMesh(mesh);
  39040. }
  39041. var meshes = this._meshes;
  39042. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  39043. mesh._geometry = this;
  39044. this._scene.pushGeometry(this);
  39045. meshes.push(mesh);
  39046. if (this.isReady()) {
  39047. this._applyToMesh(mesh);
  39048. }
  39049. else {
  39050. mesh._boundingInfo = this._boundingInfo;
  39051. }
  39052. };
  39053. Geometry.prototype._updateExtend = function (data) {
  39054. if (data === void 0) { data = null; }
  39055. if (!data) {
  39056. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39057. }
  39058. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  39059. };
  39060. Geometry.prototype._applyToMesh = function (mesh) {
  39061. var numOfMeshes = this._meshes.length;
  39062. // vertexBuffers
  39063. for (var kind in this._vertexBuffers) {
  39064. if (numOfMeshes === 1) {
  39065. this._vertexBuffers[kind].create();
  39066. }
  39067. var buffer = this._vertexBuffers[kind].getBuffer();
  39068. if (buffer)
  39069. buffer.references = numOfMeshes;
  39070. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39071. if (!this._extend) {
  39072. this._updateExtend();
  39073. }
  39074. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39075. mesh._createGlobalSubMesh(false);
  39076. //bounding info was just created again, world matrix should be applied again.
  39077. mesh._updateBoundingInfo();
  39078. }
  39079. }
  39080. // indexBuffer
  39081. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39082. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39083. }
  39084. if (this._indexBuffer) {
  39085. this._indexBuffer.references = numOfMeshes;
  39086. }
  39087. };
  39088. Geometry.prototype.notifyUpdate = function (kind) {
  39089. if (this.onGeometryUpdated) {
  39090. this.onGeometryUpdated(this, kind);
  39091. }
  39092. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  39093. var mesh = _a[_i];
  39094. mesh._markSubMeshesAsAttributesDirty();
  39095. }
  39096. };
  39097. /**
  39098. * Load the geometry if it was flagged as delay loaded
  39099. * @param scene defines the hosting scene
  39100. * @param onLoaded defines a callback called when the geometry is loaded
  39101. */
  39102. Geometry.prototype.load = function (scene, onLoaded) {
  39103. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39104. return;
  39105. }
  39106. if (this.isReady()) {
  39107. if (onLoaded) {
  39108. onLoaded();
  39109. }
  39110. return;
  39111. }
  39112. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39113. this._queueLoad(scene, onLoaded);
  39114. };
  39115. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39116. var _this = this;
  39117. if (!this.delayLoadingFile) {
  39118. return;
  39119. }
  39120. scene._addPendingData(this);
  39121. scene._loadFile(this.delayLoadingFile, function (data) {
  39122. if (!_this._delayLoadingFunction) {
  39123. return;
  39124. }
  39125. _this._delayLoadingFunction(JSON.parse(data), _this);
  39126. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39127. _this._delayInfo = [];
  39128. scene._removePendingData(_this);
  39129. var meshes = _this._meshes;
  39130. var numOfMeshes = meshes.length;
  39131. for (var index = 0; index < numOfMeshes; index++) {
  39132. _this._applyToMesh(meshes[index]);
  39133. }
  39134. if (onLoaded) {
  39135. onLoaded();
  39136. }
  39137. }, undefined, true);
  39138. };
  39139. /**
  39140. * Invert the geometry to move from a right handed system to a left handed one.
  39141. */
  39142. Geometry.prototype.toLeftHanded = function () {
  39143. // Flip faces
  39144. var tIndices = this.getIndices(false);
  39145. if (tIndices != null && tIndices.length > 0) {
  39146. for (var i = 0; i < tIndices.length; i += 3) {
  39147. var tTemp = tIndices[i + 0];
  39148. tIndices[i + 0] = tIndices[i + 2];
  39149. tIndices[i + 2] = tTemp;
  39150. }
  39151. this.setIndices(tIndices);
  39152. }
  39153. // Negate position.z
  39154. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39155. if (tPositions != null && tPositions.length > 0) {
  39156. for (var i = 0; i < tPositions.length; i += 3) {
  39157. tPositions[i + 2] = -tPositions[i + 2];
  39158. }
  39159. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39160. }
  39161. // Negate normal.z
  39162. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39163. if (tNormals != null && tNormals.length > 0) {
  39164. for (var i = 0; i < tNormals.length; i += 3) {
  39165. tNormals[i + 2] = -tNormals[i + 2];
  39166. }
  39167. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39168. }
  39169. };
  39170. // Cache
  39171. /** @hidden */
  39172. Geometry.prototype._resetPointsArrayCache = function () {
  39173. this._positions = null;
  39174. };
  39175. /** @hidden */
  39176. Geometry.prototype._generatePointsArray = function () {
  39177. if (this._positions)
  39178. return true;
  39179. this._positions = [];
  39180. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39181. if (!data) {
  39182. return false;
  39183. }
  39184. for (var index = 0; index < data.length; index += 3) {
  39185. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39186. }
  39187. return true;
  39188. };
  39189. /**
  39190. * Gets a value indicating if the geometry is disposed
  39191. * @returns true if the geometry was disposed
  39192. */
  39193. Geometry.prototype.isDisposed = function () {
  39194. return this._isDisposed;
  39195. };
  39196. Geometry.prototype._disposeVertexArrayObjects = function () {
  39197. if (this._vertexArrayObjects) {
  39198. for (var kind in this._vertexArrayObjects) {
  39199. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39200. }
  39201. this._vertexArrayObjects = {};
  39202. }
  39203. };
  39204. /**
  39205. * Free all associated resources
  39206. */
  39207. Geometry.prototype.dispose = function () {
  39208. var meshes = this._meshes;
  39209. var numOfMeshes = meshes.length;
  39210. var index;
  39211. for (index = 0; index < numOfMeshes; index++) {
  39212. this.releaseForMesh(meshes[index]);
  39213. }
  39214. this._meshes = [];
  39215. this._disposeVertexArrayObjects();
  39216. for (var kind in this._vertexBuffers) {
  39217. this._vertexBuffers[kind].dispose();
  39218. }
  39219. this._vertexBuffers = {};
  39220. this._totalVertices = 0;
  39221. if (this._indexBuffer) {
  39222. this._engine._releaseBuffer(this._indexBuffer);
  39223. }
  39224. this._indexBuffer = null;
  39225. this._indices = [];
  39226. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39227. this.delayLoadingFile = null;
  39228. this._delayLoadingFunction = null;
  39229. this._delayInfo = [];
  39230. this._boundingInfo = null;
  39231. this._scene.removeGeometry(this);
  39232. this._isDisposed = true;
  39233. };
  39234. /**
  39235. * Clone the current geometry into a new geometry
  39236. * @param id defines the unique ID of the new geometry
  39237. * @returns a new geometry object
  39238. */
  39239. Geometry.prototype.copy = function (id) {
  39240. var vertexData = new BABYLON.VertexData();
  39241. vertexData.indices = [];
  39242. var indices = this.getIndices();
  39243. if (indices) {
  39244. for (var index = 0; index < indices.length; index++) {
  39245. vertexData.indices.push(indices[index]);
  39246. }
  39247. }
  39248. var updatable = false;
  39249. var stopChecking = false;
  39250. var kind;
  39251. for (kind in this._vertexBuffers) {
  39252. // using slice() to make a copy of the array and not just reference it
  39253. var data = this.getVerticesData(kind);
  39254. if (data instanceof Float32Array) {
  39255. vertexData.set(new Float32Array(data), kind);
  39256. }
  39257. else {
  39258. vertexData.set(data.slice(0), kind);
  39259. }
  39260. if (!stopChecking) {
  39261. var vb = this.getVertexBuffer(kind);
  39262. if (vb) {
  39263. updatable = vb.isUpdatable();
  39264. stopChecking = !updatable;
  39265. }
  39266. }
  39267. }
  39268. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39269. geometry.delayLoadState = this.delayLoadState;
  39270. geometry.delayLoadingFile = this.delayLoadingFile;
  39271. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39272. for (kind in this._delayInfo) {
  39273. geometry._delayInfo = geometry._delayInfo || [];
  39274. geometry._delayInfo.push(kind);
  39275. }
  39276. // Bounding info
  39277. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39278. return geometry;
  39279. };
  39280. /**
  39281. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39282. * @return a JSON representation of the current geometry data (without the vertices data)
  39283. */
  39284. Geometry.prototype.serialize = function () {
  39285. var serializationObject = {};
  39286. serializationObject.id = this.id;
  39287. serializationObject.updatable = this._updatable;
  39288. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39289. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39290. }
  39291. return serializationObject;
  39292. };
  39293. Geometry.prototype.toNumberArray = function (origin) {
  39294. if (Array.isArray(origin)) {
  39295. return origin;
  39296. }
  39297. else {
  39298. return Array.prototype.slice.call(origin);
  39299. }
  39300. };
  39301. /**
  39302. * Serialize all vertices data into a JSON oject
  39303. * @returns a JSON representation of the current geometry data
  39304. */
  39305. Geometry.prototype.serializeVerticeData = function () {
  39306. var serializationObject = this.serialize();
  39307. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39308. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39309. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39310. serializationObject.positions._updatable = true;
  39311. }
  39312. }
  39313. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39314. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39315. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39316. serializationObject.normals._updatable = true;
  39317. }
  39318. }
  39319. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39320. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39321. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39322. serializationObject.tangets._updatable = true;
  39323. }
  39324. }
  39325. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39326. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39327. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39328. serializationObject.uvs._updatable = true;
  39329. }
  39330. }
  39331. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39332. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39333. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39334. serializationObject.uv2s._updatable = true;
  39335. }
  39336. }
  39337. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39338. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39339. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39340. serializationObject.uv3s._updatable = true;
  39341. }
  39342. }
  39343. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39344. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39345. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39346. serializationObject.uv4s._updatable = true;
  39347. }
  39348. }
  39349. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39350. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39351. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39352. serializationObject.uv5s._updatable = true;
  39353. }
  39354. }
  39355. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39356. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39357. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39358. serializationObject.uv6s._updatable = true;
  39359. }
  39360. }
  39361. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39362. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39363. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39364. serializationObject.colors._updatable = true;
  39365. }
  39366. }
  39367. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39368. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39369. serializationObject.matricesIndices._isExpanded = true;
  39370. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39371. serializationObject.matricesIndices._updatable = true;
  39372. }
  39373. }
  39374. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39375. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39376. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39377. serializationObject.matricesWeights._updatable = true;
  39378. }
  39379. }
  39380. serializationObject.indices = this.toNumberArray(this.getIndices());
  39381. return serializationObject;
  39382. };
  39383. // Statics
  39384. /**
  39385. * Extracts a clone of a mesh geometry
  39386. * @param mesh defines the source mesh
  39387. * @param id defines the unique ID of the new geometry object
  39388. * @returns the new geometry object
  39389. */
  39390. Geometry.ExtractFromMesh = function (mesh, id) {
  39391. var geometry = mesh._geometry;
  39392. if (!geometry) {
  39393. return null;
  39394. }
  39395. return geometry.copy(id);
  39396. };
  39397. /**
  39398. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39399. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39400. * Be aware Math.random() could cause collisions, but:
  39401. * "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"
  39402. * @returns a string containing a new GUID
  39403. */
  39404. Geometry.RandomId = function () {
  39405. return BABYLON.Tools.RandomId();
  39406. };
  39407. /** @hidden */
  39408. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39409. var scene = mesh.getScene();
  39410. // Geometry
  39411. var geometryId = parsedGeometry.geometryId;
  39412. if (geometryId) {
  39413. var geometry = scene.getGeometryByID(geometryId);
  39414. if (geometry) {
  39415. geometry.applyToMesh(mesh);
  39416. }
  39417. }
  39418. else if (parsedGeometry instanceof ArrayBuffer) {
  39419. var binaryInfo = mesh._binaryInfo;
  39420. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39421. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39422. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39423. }
  39424. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39425. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39426. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39427. }
  39428. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39429. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39430. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39431. }
  39432. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39433. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39434. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39435. }
  39436. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39437. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39438. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39439. }
  39440. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39441. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39442. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39443. }
  39444. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39445. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39446. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39447. }
  39448. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39449. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39450. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39451. }
  39452. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39453. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39454. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39455. }
  39456. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39457. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39458. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39459. }
  39460. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39461. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39462. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  39463. }
  39464. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39465. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39466. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39467. }
  39468. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39469. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39470. mesh.setIndices(indicesData, null);
  39471. }
  39472. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39473. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39474. mesh.subMeshes = [];
  39475. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39476. var materialIndex = subMeshesData[(i * 5) + 0];
  39477. var verticesStart = subMeshesData[(i * 5) + 1];
  39478. var verticesCount = subMeshesData[(i * 5) + 2];
  39479. var indexStart = subMeshesData[(i * 5) + 3];
  39480. var indexCount = subMeshesData[(i * 5) + 4];
  39481. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39482. }
  39483. }
  39484. }
  39485. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  39486. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  39487. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  39488. if (parsedGeometry.tangents) {
  39489. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  39490. }
  39491. if (parsedGeometry.uvs) {
  39492. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  39493. }
  39494. if (parsedGeometry.uvs2) {
  39495. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  39496. }
  39497. if (parsedGeometry.uvs3) {
  39498. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  39499. }
  39500. if (parsedGeometry.uvs4) {
  39501. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  39502. }
  39503. if (parsedGeometry.uvs5) {
  39504. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  39505. }
  39506. if (parsedGeometry.uvs6) {
  39507. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  39508. }
  39509. if (parsedGeometry.colors) {
  39510. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  39511. }
  39512. if (parsedGeometry.matricesIndices) {
  39513. if (!parsedGeometry.matricesIndices._isExpanded) {
  39514. var floatIndices = [];
  39515. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  39516. var matricesIndex = parsedGeometry.matricesIndices[i];
  39517. floatIndices.push(matricesIndex & 0x000000FF);
  39518. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39519. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39520. floatIndices.push(matricesIndex >> 24);
  39521. }
  39522. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  39523. }
  39524. else {
  39525. delete parsedGeometry.matricesIndices._isExpanded;
  39526. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  39527. }
  39528. }
  39529. if (parsedGeometry.matricesIndicesExtra) {
  39530. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  39531. var floatIndices = [];
  39532. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  39533. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  39534. floatIndices.push(matricesIndex & 0x000000FF);
  39535. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39536. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39537. floatIndices.push(matricesIndex >> 24);
  39538. }
  39539. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  39540. }
  39541. else {
  39542. delete parsedGeometry.matricesIndices._isExpanded;
  39543. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  39544. }
  39545. }
  39546. if (parsedGeometry.matricesWeights) {
  39547. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  39548. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  39549. }
  39550. if (parsedGeometry.matricesWeightsExtra) {
  39551. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  39552. }
  39553. mesh.setIndices(parsedGeometry.indices, null);
  39554. }
  39555. // SubMeshes
  39556. if (parsedGeometry.subMeshes) {
  39557. mesh.subMeshes = [];
  39558. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  39559. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  39560. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  39561. }
  39562. }
  39563. // Flat shading
  39564. if (mesh._shouldGenerateFlatShading) {
  39565. mesh.convertToFlatShadedMesh();
  39566. delete mesh._shouldGenerateFlatShading;
  39567. }
  39568. // Update
  39569. mesh.computeWorldMatrix(true);
  39570. // Octree
  39571. var sceneOctree = scene.selectionOctree;
  39572. if (sceneOctree !== undefined && sceneOctree !== null) {
  39573. sceneOctree.addMesh(mesh);
  39574. }
  39575. };
  39576. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  39577. var epsilon = 1e-3;
  39578. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  39579. return;
  39580. }
  39581. var noInfluenceBoneIndex = 0.0;
  39582. if (parsedGeometry.skeletonId > -1) {
  39583. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  39584. if (!skeleton) {
  39585. return;
  39586. }
  39587. noInfluenceBoneIndex = skeleton.bones.length;
  39588. }
  39589. else {
  39590. return;
  39591. }
  39592. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  39593. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39594. var matricesWeights = parsedGeometry.matricesWeights;
  39595. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  39596. var influencers = parsedGeometry.numBoneInfluencer;
  39597. var size = matricesWeights.length;
  39598. for (var i = 0; i < size; i += 4) {
  39599. var weight = 0.0;
  39600. var firstZeroWeight = -1;
  39601. for (var j = 0; j < 4; j++) {
  39602. var w = matricesWeights[i + j];
  39603. weight += w;
  39604. if (w < epsilon && firstZeroWeight < 0) {
  39605. firstZeroWeight = j;
  39606. }
  39607. }
  39608. if (matricesWeightsExtra) {
  39609. for (var j = 0; j < 4; j++) {
  39610. var w = matricesWeightsExtra[i + j];
  39611. weight += w;
  39612. if (w < epsilon && firstZeroWeight < 0) {
  39613. firstZeroWeight = j + 4;
  39614. }
  39615. }
  39616. }
  39617. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  39618. firstZeroWeight = influencers - 1;
  39619. }
  39620. if (weight > epsilon) {
  39621. var mweight = 1.0 / weight;
  39622. for (var j = 0; j < 4; j++) {
  39623. matricesWeights[i + j] *= mweight;
  39624. }
  39625. if (matricesWeightsExtra) {
  39626. for (var j = 0; j < 4; j++) {
  39627. matricesWeightsExtra[i + j] *= mweight;
  39628. }
  39629. }
  39630. }
  39631. else {
  39632. if (firstZeroWeight >= 4) {
  39633. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  39634. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  39635. }
  39636. else {
  39637. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  39638. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  39639. }
  39640. }
  39641. }
  39642. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  39643. if (parsedGeometry.matricesWeightsExtra) {
  39644. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  39645. }
  39646. };
  39647. /**
  39648. * Create a new geometry from persisted data (Using .babylon file format)
  39649. * @param parsedVertexData defines the persisted data
  39650. * @param scene defines the hosting scene
  39651. * @param rootUrl defines the root url to use to load assets (like delayed data)
  39652. * @returns the new geometry object
  39653. */
  39654. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  39655. if (scene.getGeometryByID(parsedVertexData.id)) {
  39656. return null; // null since geometry could be something else than a box...
  39657. }
  39658. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  39659. if (BABYLON.Tags) {
  39660. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  39661. }
  39662. if (parsedVertexData.delayLoadingFile) {
  39663. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  39664. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  39665. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  39666. geometry._delayInfo = [];
  39667. if (parsedVertexData.hasUVs) {
  39668. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  39669. }
  39670. if (parsedVertexData.hasUVs2) {
  39671. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  39672. }
  39673. if (parsedVertexData.hasUVs3) {
  39674. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  39675. }
  39676. if (parsedVertexData.hasUVs4) {
  39677. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  39678. }
  39679. if (parsedVertexData.hasUVs5) {
  39680. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  39681. }
  39682. if (parsedVertexData.hasUVs6) {
  39683. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  39684. }
  39685. if (parsedVertexData.hasColors) {
  39686. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  39687. }
  39688. if (parsedVertexData.hasMatricesIndices) {
  39689. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39690. }
  39691. if (parsedVertexData.hasMatricesWeights) {
  39692. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39693. }
  39694. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  39695. }
  39696. else {
  39697. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  39698. }
  39699. scene.pushGeometry(geometry, true);
  39700. return geometry;
  39701. };
  39702. return Geometry;
  39703. }());
  39704. BABYLON.Geometry = Geometry;
  39705. // Primitives
  39706. /// Abstract class
  39707. /**
  39708. * Abstract class used to provide common services for all typed geometries
  39709. * @hidden
  39710. */
  39711. var _PrimitiveGeometry = /** @class */ (function (_super) {
  39712. __extends(_PrimitiveGeometry, _super);
  39713. /**
  39714. * Creates a new typed geometry
  39715. * @param id defines the unique ID of the geometry
  39716. * @param scene defines the hosting scene
  39717. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39718. * @param mesh defines the hosting mesh (can be null)
  39719. */
  39720. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  39721. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  39722. if (mesh === void 0) { mesh = null; }
  39723. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  39724. _this._canBeRegenerated = _canBeRegenerated;
  39725. _this._beingRegenerated = true;
  39726. _this.regenerate();
  39727. _this._beingRegenerated = false;
  39728. return _this;
  39729. }
  39730. /**
  39731. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  39732. * @returns true if the geometry can be regenerated
  39733. */
  39734. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  39735. return this._canBeRegenerated;
  39736. };
  39737. /**
  39738. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  39739. */
  39740. _PrimitiveGeometry.prototype.regenerate = function () {
  39741. if (!this._canBeRegenerated) {
  39742. return;
  39743. }
  39744. this._beingRegenerated = true;
  39745. this.setAllVerticesData(this._regenerateVertexData(), false);
  39746. this._beingRegenerated = false;
  39747. };
  39748. /**
  39749. * Clone the geometry
  39750. * @param id defines the unique ID of the new geometry
  39751. * @returns the new geometry
  39752. */
  39753. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  39754. return _super.prototype.copy.call(this, id);
  39755. };
  39756. // overrides
  39757. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39758. if (!this._beingRegenerated) {
  39759. return;
  39760. }
  39761. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  39762. };
  39763. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  39764. if (!this._beingRegenerated) {
  39765. return;
  39766. }
  39767. _super.prototype.setVerticesData.call(this, kind, data, false);
  39768. };
  39769. // to override
  39770. /** @hidden */
  39771. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  39772. throw new Error("Abstract method");
  39773. };
  39774. _PrimitiveGeometry.prototype.copy = function (id) {
  39775. throw new Error("Must be overriden in sub-classes.");
  39776. };
  39777. _PrimitiveGeometry.prototype.serialize = function () {
  39778. var serializationObject = _super.prototype.serialize.call(this);
  39779. serializationObject.canBeRegenerated = this.canBeRegenerated();
  39780. return serializationObject;
  39781. };
  39782. return _PrimitiveGeometry;
  39783. }(Geometry));
  39784. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  39785. /**
  39786. * Creates a ribbon geometry
  39787. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  39788. */
  39789. var RibbonGeometry = /** @class */ (function (_super) {
  39790. __extends(RibbonGeometry, _super);
  39791. /**
  39792. * Creates a ribbon geometry
  39793. * @param id defines the unique ID of the geometry
  39794. * @param scene defines the hosting scene
  39795. * @param pathArray defines the array of paths to use
  39796. * @param closeArray defines if the last path and the first path must be joined
  39797. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  39798. * @param offset defines the offset between points
  39799. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39800. * @param mesh defines the hosting mesh (can be null)
  39801. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39802. */
  39803. function RibbonGeometry(id, scene,
  39804. /**
  39805. * Defines the array of paths to use
  39806. */
  39807. pathArray,
  39808. /**
  39809. * Defines if the last and first points of each path in your pathArray must be joined
  39810. */
  39811. closeArray,
  39812. /**
  39813. * Defines if the last and first points of each path in your pathArray must be joined
  39814. */
  39815. closePath,
  39816. /**
  39817. * Defines the offset between points
  39818. */
  39819. offset, canBeRegenerated, mesh,
  39820. /**
  39821. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39822. */
  39823. side) {
  39824. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39825. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39826. _this.pathArray = pathArray;
  39827. _this.closeArray = closeArray;
  39828. _this.closePath = closePath;
  39829. _this.offset = offset;
  39830. _this.side = side;
  39831. return _this;
  39832. }
  39833. /** @hidden */
  39834. RibbonGeometry.prototype._regenerateVertexData = function () {
  39835. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  39836. };
  39837. RibbonGeometry.prototype.copy = function (id) {
  39838. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  39839. };
  39840. return RibbonGeometry;
  39841. }(_PrimitiveGeometry));
  39842. BABYLON.RibbonGeometry = RibbonGeometry;
  39843. /**
  39844. * Creates a box geometry
  39845. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  39846. */
  39847. var BoxGeometry = /** @class */ (function (_super) {
  39848. __extends(BoxGeometry, _super);
  39849. /**
  39850. * Creates a box geometry
  39851. * @param id defines the unique ID of the geometry
  39852. * @param scene defines the hosting scene
  39853. * @param size defines the zise of the box (width, height and depth are the same)
  39854. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39855. * @param mesh defines the hosting mesh (can be null)
  39856. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39857. */
  39858. function BoxGeometry(id, scene,
  39859. /**
  39860. * Defines the zise of the box (width, height and depth are the same)
  39861. */
  39862. size, canBeRegenerated, mesh,
  39863. /**
  39864. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39865. */
  39866. side) {
  39867. if (mesh === void 0) { mesh = null; }
  39868. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39869. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39870. _this.size = size;
  39871. _this.side = side;
  39872. return _this;
  39873. }
  39874. BoxGeometry.prototype._regenerateVertexData = function () {
  39875. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  39876. };
  39877. BoxGeometry.prototype.copy = function (id) {
  39878. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  39879. };
  39880. BoxGeometry.prototype.serialize = function () {
  39881. var serializationObject = _super.prototype.serialize.call(this);
  39882. serializationObject.size = this.size;
  39883. return serializationObject;
  39884. };
  39885. BoxGeometry.Parse = function (parsedBox, scene) {
  39886. if (scene.getGeometryByID(parsedBox.id)) {
  39887. return null; // null since geometry could be something else than a box...
  39888. }
  39889. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  39890. if (BABYLON.Tags) {
  39891. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  39892. }
  39893. scene.pushGeometry(box, true);
  39894. return box;
  39895. };
  39896. return BoxGeometry;
  39897. }(_PrimitiveGeometry));
  39898. BABYLON.BoxGeometry = BoxGeometry;
  39899. /**
  39900. * Creates a sphere geometry
  39901. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  39902. */
  39903. var SphereGeometry = /** @class */ (function (_super) {
  39904. __extends(SphereGeometry, _super);
  39905. /**
  39906. * Create a new sphere geometry
  39907. * @param id defines the unique ID of the geometry
  39908. * @param scene defines the hosting scene
  39909. * @param segments defines the number of segments to use to create the sphere
  39910. * @param diameter defines the diameter of the sphere
  39911. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39912. * @param mesh defines the hosting mesh (can be null)
  39913. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39914. */
  39915. function SphereGeometry(id, scene,
  39916. /**
  39917. * Defines the number of segments to use to create the sphere
  39918. */
  39919. segments,
  39920. /**
  39921. * Defines the diameter of the sphere
  39922. */
  39923. diameter, canBeRegenerated, mesh,
  39924. /**
  39925. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39926. */
  39927. side) {
  39928. if (mesh === void 0) { mesh = null; }
  39929. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39930. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39931. _this.segments = segments;
  39932. _this.diameter = diameter;
  39933. _this.side = side;
  39934. return _this;
  39935. }
  39936. SphereGeometry.prototype._regenerateVertexData = function () {
  39937. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  39938. };
  39939. SphereGeometry.prototype.copy = function (id) {
  39940. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  39941. };
  39942. SphereGeometry.prototype.serialize = function () {
  39943. var serializationObject = _super.prototype.serialize.call(this);
  39944. serializationObject.segments = this.segments;
  39945. serializationObject.diameter = this.diameter;
  39946. return serializationObject;
  39947. };
  39948. SphereGeometry.Parse = function (parsedSphere, scene) {
  39949. if (scene.getGeometryByID(parsedSphere.id)) {
  39950. return null; // null since geometry could be something else than a sphere...
  39951. }
  39952. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  39953. if (BABYLON.Tags) {
  39954. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  39955. }
  39956. scene.pushGeometry(sphere, true);
  39957. return sphere;
  39958. };
  39959. return SphereGeometry;
  39960. }(_PrimitiveGeometry));
  39961. BABYLON.SphereGeometry = SphereGeometry;
  39962. /**
  39963. * Creates a disc geometry
  39964. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  39965. */
  39966. var DiscGeometry = /** @class */ (function (_super) {
  39967. __extends(DiscGeometry, _super);
  39968. /**
  39969. * Creates a new disc geometry
  39970. * @param id defines the unique ID of the geometry
  39971. * @param scene defines the hosting scene
  39972. * @param radius defines the radius of the disc
  39973. * @param tessellation defines the tesselation factor to apply to the disc
  39974. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39975. * @param mesh defines the hosting mesh (can be null)
  39976. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39977. */
  39978. function DiscGeometry(id, scene,
  39979. /**
  39980. * Defines the radius of the disc
  39981. */
  39982. radius,
  39983. /**
  39984. * Defines the tesselation factor to apply to the disc
  39985. */
  39986. tessellation, canBeRegenerated, mesh,
  39987. /**
  39988. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39989. */
  39990. side) {
  39991. if (mesh === void 0) { mesh = null; }
  39992. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39993. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39994. _this.radius = radius;
  39995. _this.tessellation = tessellation;
  39996. _this.side = side;
  39997. return _this;
  39998. }
  39999. DiscGeometry.prototype._regenerateVertexData = function () {
  40000. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  40001. };
  40002. DiscGeometry.prototype.copy = function (id) {
  40003. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  40004. };
  40005. return DiscGeometry;
  40006. }(_PrimitiveGeometry));
  40007. BABYLON.DiscGeometry = DiscGeometry;
  40008. /**
  40009. * Creates a new cylinder geometry
  40010. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  40011. */
  40012. var CylinderGeometry = /** @class */ (function (_super) {
  40013. __extends(CylinderGeometry, _super);
  40014. /**
  40015. * Creates a new cylinder geometry
  40016. * @param id defines the unique ID of the geometry
  40017. * @param scene defines the hosting scene
  40018. * @param height defines the height of the cylinder
  40019. * @param diameterTop defines the diameter of the cylinder's top cap
  40020. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  40021. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  40022. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  40023. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40024. * @param mesh defines the hosting mesh (can be null)
  40025. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40026. */
  40027. function CylinderGeometry(id, scene,
  40028. /**
  40029. * Defines the height of the cylinder
  40030. */
  40031. height,
  40032. /**
  40033. * Defines the diameter of the cylinder's top cap
  40034. */
  40035. diameterTop,
  40036. /**
  40037. * Defines the diameter of the cylinder's bottom cap
  40038. */
  40039. diameterBottom,
  40040. /**
  40041. * Defines the tessellation factor to apply to the cylinder
  40042. */
  40043. tessellation,
  40044. /**
  40045. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  40046. */
  40047. subdivisions, canBeRegenerated, mesh,
  40048. /**
  40049. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40050. */
  40051. side) {
  40052. if (subdivisions === void 0) { subdivisions = 1; }
  40053. if (mesh === void 0) { mesh = null; }
  40054. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40055. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40056. _this.height = height;
  40057. _this.diameterTop = diameterTop;
  40058. _this.diameterBottom = diameterBottom;
  40059. _this.tessellation = tessellation;
  40060. _this.subdivisions = subdivisions;
  40061. _this.side = side;
  40062. return _this;
  40063. }
  40064. CylinderGeometry.prototype._regenerateVertexData = function () {
  40065. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  40066. };
  40067. CylinderGeometry.prototype.copy = function (id) {
  40068. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40069. };
  40070. CylinderGeometry.prototype.serialize = function () {
  40071. var serializationObject = _super.prototype.serialize.call(this);
  40072. serializationObject.height = this.height;
  40073. serializationObject.diameterTop = this.diameterTop;
  40074. serializationObject.diameterBottom = this.diameterBottom;
  40075. serializationObject.tessellation = this.tessellation;
  40076. return serializationObject;
  40077. };
  40078. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  40079. if (scene.getGeometryByID(parsedCylinder.id)) {
  40080. return null; // null since geometry could be something else than a cylinder...
  40081. }
  40082. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40083. if (BABYLON.Tags) {
  40084. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40085. }
  40086. scene.pushGeometry(cylinder, true);
  40087. return cylinder;
  40088. };
  40089. return CylinderGeometry;
  40090. }(_PrimitiveGeometry));
  40091. BABYLON.CylinderGeometry = CylinderGeometry;
  40092. /**
  40093. * Creates a new torus geometry
  40094. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  40095. */
  40096. var TorusGeometry = /** @class */ (function (_super) {
  40097. __extends(TorusGeometry, _super);
  40098. /**
  40099. * Creates a new torus geometry
  40100. * @param id defines the unique ID of the geometry
  40101. * @param scene defines the hosting scene
  40102. * @param diameter defines the diameter of the torus
  40103. * @param thickness defines the thickness of the torus (ie. internal diameter)
  40104. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  40105. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40106. * @param mesh defines the hosting mesh (can be null)
  40107. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40108. */
  40109. function TorusGeometry(id, scene,
  40110. /**
  40111. * Defines the diameter of the torus
  40112. */
  40113. diameter,
  40114. /**
  40115. * Defines the thickness of the torus (ie. internal diameter)
  40116. */
  40117. thickness,
  40118. /**
  40119. * Defines the tesselation factor to apply to the torus
  40120. */
  40121. tessellation, canBeRegenerated, mesh,
  40122. /**
  40123. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40124. */
  40125. side) {
  40126. if (mesh === void 0) { mesh = null; }
  40127. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40128. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40129. _this.diameter = diameter;
  40130. _this.thickness = thickness;
  40131. _this.tessellation = tessellation;
  40132. _this.side = side;
  40133. return _this;
  40134. }
  40135. TorusGeometry.prototype._regenerateVertexData = function () {
  40136. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40137. };
  40138. TorusGeometry.prototype.copy = function (id) {
  40139. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40140. };
  40141. TorusGeometry.prototype.serialize = function () {
  40142. var serializationObject = _super.prototype.serialize.call(this);
  40143. serializationObject.diameter = this.diameter;
  40144. serializationObject.thickness = this.thickness;
  40145. serializationObject.tessellation = this.tessellation;
  40146. return serializationObject;
  40147. };
  40148. TorusGeometry.Parse = function (parsedTorus, scene) {
  40149. if (scene.getGeometryByID(parsedTorus.id)) {
  40150. return null; // null since geometry could be something else than a torus...
  40151. }
  40152. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40153. if (BABYLON.Tags) {
  40154. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40155. }
  40156. scene.pushGeometry(torus, true);
  40157. return torus;
  40158. };
  40159. return TorusGeometry;
  40160. }(_PrimitiveGeometry));
  40161. BABYLON.TorusGeometry = TorusGeometry;
  40162. /**
  40163. * Creates a new ground geometry
  40164. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40165. */
  40166. var GroundGeometry = /** @class */ (function (_super) {
  40167. __extends(GroundGeometry, _super);
  40168. /**
  40169. * Creates a new ground geometry
  40170. * @param id defines the unique ID of the geometry
  40171. * @param scene defines the hosting scene
  40172. * @param width defines the width of the ground
  40173. * @param height defines the height of the ground
  40174. * @param subdivisions defines the subdivisions to apply to the ground
  40175. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40176. * @param mesh defines the hosting mesh (can be null)
  40177. */
  40178. function GroundGeometry(id, scene,
  40179. /**
  40180. * Defines the width of the ground
  40181. */
  40182. width,
  40183. /**
  40184. * Defines the height of the ground
  40185. */
  40186. height,
  40187. /**
  40188. * Defines the subdivisions to apply to the ground
  40189. */
  40190. subdivisions, canBeRegenerated, mesh) {
  40191. if (mesh === void 0) { mesh = null; }
  40192. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40193. _this.width = width;
  40194. _this.height = height;
  40195. _this.subdivisions = subdivisions;
  40196. return _this;
  40197. }
  40198. GroundGeometry.prototype._regenerateVertexData = function () {
  40199. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40200. };
  40201. GroundGeometry.prototype.copy = function (id) {
  40202. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40203. };
  40204. GroundGeometry.prototype.serialize = function () {
  40205. var serializationObject = _super.prototype.serialize.call(this);
  40206. serializationObject.width = this.width;
  40207. serializationObject.height = this.height;
  40208. serializationObject.subdivisions = this.subdivisions;
  40209. return serializationObject;
  40210. };
  40211. GroundGeometry.Parse = function (parsedGround, scene) {
  40212. if (scene.getGeometryByID(parsedGround.id)) {
  40213. return null; // null since geometry could be something else than a ground...
  40214. }
  40215. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40216. if (BABYLON.Tags) {
  40217. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40218. }
  40219. scene.pushGeometry(ground, true);
  40220. return ground;
  40221. };
  40222. return GroundGeometry;
  40223. }(_PrimitiveGeometry));
  40224. BABYLON.GroundGeometry = GroundGeometry;
  40225. /**
  40226. * Creates a tiled ground geometry
  40227. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40228. */
  40229. var TiledGroundGeometry = /** @class */ (function (_super) {
  40230. __extends(TiledGroundGeometry, _super);
  40231. /**
  40232. * Creates a tiled ground geometry
  40233. * @param id defines the unique ID of the geometry
  40234. * @param scene defines the hosting scene
  40235. * @param xmin defines the minimum value on X axis
  40236. * @param zmin defines the minimum value on Z axis
  40237. * @param xmax defines the maximum value on X axis
  40238. * @param zmax defines the maximum value on Z axis
  40239. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40240. * @param precision defines the precision to use when computing the tiles
  40241. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40242. * @param mesh defines the hosting mesh (can be null)
  40243. */
  40244. function TiledGroundGeometry(id, scene,
  40245. /**
  40246. * Defines the minimum value on X axis
  40247. */
  40248. xmin,
  40249. /**
  40250. * Defines the minimum value on Z axis
  40251. */
  40252. zmin,
  40253. /**
  40254. * Defines the maximum value on X axis
  40255. */
  40256. xmax,
  40257. /**
  40258. * Defines the maximum value on Z axis
  40259. */
  40260. zmax,
  40261. /**
  40262. * Defines the subdivisions to apply to the ground
  40263. */
  40264. subdivisions,
  40265. /**
  40266. * Defines the precision to use when computing the tiles
  40267. */
  40268. precision, canBeRegenerated, mesh) {
  40269. if (mesh === void 0) { mesh = null; }
  40270. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40271. _this.xmin = xmin;
  40272. _this.zmin = zmin;
  40273. _this.xmax = xmax;
  40274. _this.zmax = zmax;
  40275. _this.subdivisions = subdivisions;
  40276. _this.precision = precision;
  40277. return _this;
  40278. }
  40279. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40280. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40281. };
  40282. TiledGroundGeometry.prototype.copy = function (id) {
  40283. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40284. };
  40285. return TiledGroundGeometry;
  40286. }(_PrimitiveGeometry));
  40287. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40288. /**
  40289. * Creates a plane geometry
  40290. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40291. */
  40292. var PlaneGeometry = /** @class */ (function (_super) {
  40293. __extends(PlaneGeometry, _super);
  40294. /**
  40295. * Creates a plane geometry
  40296. * @param id defines the unique ID of the geometry
  40297. * @param scene defines the hosting scene
  40298. * @param size defines the size of the plane (width === height)
  40299. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40300. * @param mesh defines the hosting mesh (can be null)
  40301. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40302. */
  40303. function PlaneGeometry(id, scene,
  40304. /**
  40305. * Defines the size of the plane (width === height)
  40306. */
  40307. size, canBeRegenerated, mesh,
  40308. /**
  40309. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40310. */
  40311. side) {
  40312. if (mesh === void 0) { mesh = null; }
  40313. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40314. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40315. _this.size = size;
  40316. _this.side = side;
  40317. return _this;
  40318. }
  40319. PlaneGeometry.prototype._regenerateVertexData = function () {
  40320. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40321. };
  40322. PlaneGeometry.prototype.copy = function (id) {
  40323. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40324. };
  40325. PlaneGeometry.prototype.serialize = function () {
  40326. var serializationObject = _super.prototype.serialize.call(this);
  40327. serializationObject.size = this.size;
  40328. return serializationObject;
  40329. };
  40330. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40331. if (scene.getGeometryByID(parsedPlane.id)) {
  40332. return null; // null since geometry could be something else than a ground...
  40333. }
  40334. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40335. if (BABYLON.Tags) {
  40336. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40337. }
  40338. scene.pushGeometry(plane, true);
  40339. return plane;
  40340. };
  40341. return PlaneGeometry;
  40342. }(_PrimitiveGeometry));
  40343. BABYLON.PlaneGeometry = PlaneGeometry;
  40344. /**
  40345. * Creates a torus knot geometry
  40346. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40347. */
  40348. var TorusKnotGeometry = /** @class */ (function (_super) {
  40349. __extends(TorusKnotGeometry, _super);
  40350. /**
  40351. * Creates a torus knot geometry
  40352. * @param id defines the unique ID of the geometry
  40353. * @param scene defines the hosting scene
  40354. * @param radius defines the radius of the torus knot
  40355. * @param tube defines the thickness of the torus knot tube
  40356. * @param radialSegments defines the number of radial segments
  40357. * @param tubularSegments defines the number of tubular segments
  40358. * @param p defines the first number of windings
  40359. * @param q defines the second number of windings
  40360. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40361. * @param mesh defines the hosting mesh (can be null)
  40362. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40363. */
  40364. function TorusKnotGeometry(id, scene,
  40365. /**
  40366. * Defines the radius of the torus knot
  40367. */
  40368. radius,
  40369. /**
  40370. * Defines the thickness of the torus knot tube
  40371. */
  40372. tube,
  40373. /**
  40374. * Defines the number of radial segments
  40375. */
  40376. radialSegments,
  40377. /**
  40378. * Defines the number of tubular segments
  40379. */
  40380. tubularSegments,
  40381. /**
  40382. * Defines the first number of windings
  40383. */
  40384. p,
  40385. /**
  40386. * Defines the second number of windings
  40387. */
  40388. q, canBeRegenerated, mesh,
  40389. /**
  40390. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40391. */
  40392. side) {
  40393. if (mesh === void 0) { mesh = null; }
  40394. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40395. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40396. _this.radius = radius;
  40397. _this.tube = tube;
  40398. _this.radialSegments = radialSegments;
  40399. _this.tubularSegments = tubularSegments;
  40400. _this.p = p;
  40401. _this.q = q;
  40402. _this.side = side;
  40403. return _this;
  40404. }
  40405. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40406. 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 });
  40407. };
  40408. TorusKnotGeometry.prototype.copy = function (id) {
  40409. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40410. };
  40411. TorusKnotGeometry.prototype.serialize = function () {
  40412. var serializationObject = _super.prototype.serialize.call(this);
  40413. serializationObject.radius = this.radius;
  40414. serializationObject.tube = this.tube;
  40415. serializationObject.radialSegments = this.radialSegments;
  40416. serializationObject.tubularSegments = this.tubularSegments;
  40417. serializationObject.p = this.p;
  40418. serializationObject.q = this.q;
  40419. return serializationObject;
  40420. };
  40421. ;
  40422. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40423. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40424. return null; // null since geometry could be something else than a ground...
  40425. }
  40426. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40427. if (BABYLON.Tags) {
  40428. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40429. }
  40430. scene.pushGeometry(torusKnot, true);
  40431. return torusKnot;
  40432. };
  40433. return TorusKnotGeometry;
  40434. }(_PrimitiveGeometry));
  40435. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40436. //}
  40437. })(BABYLON || (BABYLON = {}));
  40438. //# sourceMappingURL=babylon.geometry.js.map
  40439. var BABYLON;
  40440. (function (BABYLON) {
  40441. /**
  40442. * PostProcessManager is used to manage one or more post processes or post process pipelines
  40443. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  40444. */
  40445. var PostProcessManager = /** @class */ (function () {
  40446. /**
  40447. * Creates a new instance PostProcess
  40448. * @param scene The scene that the post process is associated with.
  40449. */
  40450. function PostProcessManager(scene) {
  40451. this._vertexBuffers = {};
  40452. this._scene = scene;
  40453. }
  40454. PostProcessManager.prototype._prepareBuffers = function () {
  40455. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  40456. return;
  40457. }
  40458. // VBO
  40459. var vertices = [];
  40460. vertices.push(1, 1);
  40461. vertices.push(-1, 1);
  40462. vertices.push(-1, -1);
  40463. vertices.push(1, -1);
  40464. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  40465. this._buildIndexBuffer();
  40466. };
  40467. PostProcessManager.prototype._buildIndexBuffer = function () {
  40468. // Indices
  40469. var indices = [];
  40470. indices.push(0);
  40471. indices.push(1);
  40472. indices.push(2);
  40473. indices.push(0);
  40474. indices.push(2);
  40475. indices.push(3);
  40476. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  40477. };
  40478. /**
  40479. * Rebuilds the vertex buffers of the manager.
  40480. */
  40481. PostProcessManager.prototype._rebuild = function () {
  40482. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40483. if (!vb) {
  40484. return;
  40485. }
  40486. vb._rebuild();
  40487. this._buildIndexBuffer();
  40488. };
  40489. // Methods
  40490. /**
  40491. * Prepares a frame to be run through a post process.
  40492. * @param sourceTexture The input texture to the post procesess. (default: null)
  40493. * @param postProcesses An array of post processes to be run. (default: null)
  40494. * @returns True if the post processes were able to be run.
  40495. */
  40496. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  40497. if (sourceTexture === void 0) { sourceTexture = null; }
  40498. if (postProcesses === void 0) { postProcesses = null; }
  40499. var camera = this._scene.activeCamera;
  40500. if (!camera) {
  40501. return false;
  40502. }
  40503. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  40504. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  40505. return false;
  40506. }
  40507. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  40508. return true;
  40509. };
  40510. /**
  40511. * Manually render a set of post processes to a texture.
  40512. * @param postProcesses An array of post processes to be run.
  40513. * @param targetTexture The target texture to render to.
  40514. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  40515. */
  40516. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  40517. if (targetTexture === void 0) { targetTexture = null; }
  40518. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  40519. var engine = this._scene.getEngine();
  40520. for (var index = 0; index < postProcesses.length; index++) {
  40521. if (index < postProcesses.length - 1) {
  40522. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  40523. }
  40524. else {
  40525. if (targetTexture) {
  40526. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  40527. }
  40528. else {
  40529. engine.restoreDefaultFramebuffer();
  40530. }
  40531. }
  40532. var pp = postProcesses[index];
  40533. var effect = pp.apply();
  40534. if (effect) {
  40535. pp.onBeforeRenderObservable.notifyObservers(effect);
  40536. // VBOs
  40537. this._prepareBuffers();
  40538. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  40539. // Draw order
  40540. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  40541. pp.onAfterRenderObservable.notifyObservers(effect);
  40542. }
  40543. }
  40544. // Restore depth buffer
  40545. engine.setDepthBuffer(true);
  40546. engine.setDepthWrite(true);
  40547. };
  40548. /**
  40549. * Finalize the result of the output of the postprocesses.
  40550. * @param doNotPresent If true the result will not be displayed to the screen.
  40551. * @param targetTexture The target texture to render to.
  40552. * @param faceIndex The index of the face to bind the target texture to.
  40553. * @param postProcesses The array of post processes to render.
  40554. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  40555. */
  40556. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  40557. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  40558. var camera = this._scene.activeCamera;
  40559. if (!camera) {
  40560. return;
  40561. }
  40562. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  40563. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  40564. return;
  40565. }
  40566. var engine = this._scene.getEngine();
  40567. for (var index = 0, len = postProcesses.length; index < len; index++) {
  40568. var pp = postProcesses[index];
  40569. if (index < len - 1) {
  40570. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  40571. }
  40572. else {
  40573. if (targetTexture) {
  40574. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  40575. pp._outputTexture = targetTexture;
  40576. }
  40577. else {
  40578. engine.restoreDefaultFramebuffer();
  40579. pp._outputTexture = null;
  40580. }
  40581. }
  40582. if (doNotPresent) {
  40583. break;
  40584. }
  40585. var effect = pp.apply();
  40586. if (effect) {
  40587. pp.onBeforeRenderObservable.notifyObservers(effect);
  40588. // VBOs
  40589. this._prepareBuffers();
  40590. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  40591. // Draw order
  40592. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  40593. pp.onAfterRenderObservable.notifyObservers(effect);
  40594. }
  40595. }
  40596. // Restore states
  40597. engine.setDepthBuffer(true);
  40598. engine.setDepthWrite(true);
  40599. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  40600. };
  40601. /**
  40602. * Disposes of the post process manager.
  40603. */
  40604. PostProcessManager.prototype.dispose = function () {
  40605. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40606. if (buffer) {
  40607. buffer.dispose();
  40608. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  40609. }
  40610. if (this._indexBuffer) {
  40611. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  40612. this._indexBuffer = null;
  40613. }
  40614. };
  40615. return PostProcessManager;
  40616. }());
  40617. BABYLON.PostProcessManager = PostProcessManager;
  40618. })(BABYLON || (BABYLON = {}));
  40619. //# sourceMappingURL=babylon.postProcessManager.js.map
  40620. var BABYLON;
  40621. (function (BABYLON) {
  40622. /**
  40623. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40624. */
  40625. var PerformanceMonitor = /** @class */ (function () {
  40626. /**
  40627. * constructor
  40628. * @param frameSampleSize The number of samples required to saturate the sliding window
  40629. */
  40630. function PerformanceMonitor(frameSampleSize) {
  40631. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40632. this._enabled = true;
  40633. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40634. }
  40635. /**
  40636. * Samples current frame
  40637. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40638. */
  40639. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  40640. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  40641. if (!this._enabled)
  40642. return;
  40643. if (this._lastFrameTimeMs != null) {
  40644. var dt = timeMs - this._lastFrameTimeMs;
  40645. this._rollingFrameTime.add(dt);
  40646. }
  40647. this._lastFrameTimeMs = timeMs;
  40648. };
  40649. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  40650. /**
  40651. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40652. * @return Average frame time in milliseconds
  40653. */
  40654. get: function () {
  40655. return this._rollingFrameTime.average;
  40656. },
  40657. enumerable: true,
  40658. configurable: true
  40659. });
  40660. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  40661. /**
  40662. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40663. * @return Frame time variance in milliseconds squared
  40664. */
  40665. get: function () {
  40666. return this._rollingFrameTime.variance;
  40667. },
  40668. enumerable: true,
  40669. configurable: true
  40670. });
  40671. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  40672. /**
  40673. * Returns the frame time of the most recent frame
  40674. * @return Frame time in milliseconds
  40675. */
  40676. get: function () {
  40677. return this._rollingFrameTime.history(0);
  40678. },
  40679. enumerable: true,
  40680. configurable: true
  40681. });
  40682. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  40683. /**
  40684. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  40685. * @return Framerate in frames per second
  40686. */
  40687. get: function () {
  40688. return 1000.0 / this._rollingFrameTime.average;
  40689. },
  40690. enumerable: true,
  40691. configurable: true
  40692. });
  40693. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  40694. /**
  40695. * Returns the average framerate in frames per second using the most recent frame time
  40696. * @return Framerate in frames per second
  40697. */
  40698. get: function () {
  40699. var history = this._rollingFrameTime.history(0);
  40700. if (history === 0) {
  40701. return 0;
  40702. }
  40703. return 1000.0 / history;
  40704. },
  40705. enumerable: true,
  40706. configurable: true
  40707. });
  40708. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  40709. /**
  40710. * Returns true if enough samples have been taken to completely fill the sliding window
  40711. * @return true if saturated
  40712. */
  40713. get: function () {
  40714. return this._rollingFrameTime.isSaturated();
  40715. },
  40716. enumerable: true,
  40717. configurable: true
  40718. });
  40719. /**
  40720. * Enables contributions to the sliding window sample set
  40721. */
  40722. PerformanceMonitor.prototype.enable = function () {
  40723. this._enabled = true;
  40724. };
  40725. /**
  40726. * Disables contributions to the sliding window sample set
  40727. * Samples will not be interpolated over the disabled period
  40728. */
  40729. PerformanceMonitor.prototype.disable = function () {
  40730. this._enabled = false;
  40731. //clear last sample to avoid interpolating over the disabled period when next enabled
  40732. this._lastFrameTimeMs = null;
  40733. };
  40734. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  40735. /**
  40736. * Returns true if sampling is enabled
  40737. * @return true if enabled
  40738. */
  40739. get: function () {
  40740. return this._enabled;
  40741. },
  40742. enumerable: true,
  40743. configurable: true
  40744. });
  40745. /**
  40746. * Resets performance monitor
  40747. */
  40748. PerformanceMonitor.prototype.reset = function () {
  40749. //clear last sample to avoid interpolating over the disabled period when next enabled
  40750. this._lastFrameTimeMs = null;
  40751. //wipe record
  40752. this._rollingFrameTime.reset();
  40753. };
  40754. return PerformanceMonitor;
  40755. }());
  40756. BABYLON.PerformanceMonitor = PerformanceMonitor;
  40757. /**
  40758. * RollingAverage
  40759. *
  40760. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  40761. */
  40762. var RollingAverage = /** @class */ (function () {
  40763. /**
  40764. * constructor
  40765. * @param length The number of samples required to saturate the sliding window
  40766. */
  40767. function RollingAverage(length) {
  40768. this._samples = new Array(length);
  40769. this.reset();
  40770. }
  40771. /**
  40772. * Adds a sample to the sample set
  40773. * @param v The sample value
  40774. */
  40775. RollingAverage.prototype.add = function (v) {
  40776. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  40777. var delta;
  40778. //we need to check if we've already wrapped round
  40779. if (this.isSaturated()) {
  40780. //remove bottom of stack from mean
  40781. var bottomValue = this._samples[this._pos];
  40782. delta = bottomValue - this.average;
  40783. this.average -= delta / (this._sampleCount - 1);
  40784. this._m2 -= delta * (bottomValue - this.average);
  40785. }
  40786. else {
  40787. this._sampleCount++;
  40788. }
  40789. //add new value to mean
  40790. delta = v - this.average;
  40791. this.average += delta / (this._sampleCount);
  40792. this._m2 += delta * (v - this.average);
  40793. //set the new variance
  40794. this.variance = this._m2 / (this._sampleCount - 1);
  40795. this._samples[this._pos] = v;
  40796. this._pos++;
  40797. this._pos %= this._samples.length; //positive wrap around
  40798. };
  40799. /**
  40800. * Returns previously added values or null if outside of history or outside the sliding window domain
  40801. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  40802. * @return Value previously recorded with add() or null if outside of range
  40803. */
  40804. RollingAverage.prototype.history = function (i) {
  40805. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  40806. return 0;
  40807. }
  40808. var i0 = this._wrapPosition(this._pos - 1.0);
  40809. return this._samples[this._wrapPosition(i0 - i)];
  40810. };
  40811. /**
  40812. * Returns true if enough samples have been taken to completely fill the sliding window
  40813. * @return true if sample-set saturated
  40814. */
  40815. RollingAverage.prototype.isSaturated = function () {
  40816. return this._sampleCount >= this._samples.length;
  40817. };
  40818. /**
  40819. * Resets the rolling average (equivalent to 0 samples taken so far)
  40820. */
  40821. RollingAverage.prototype.reset = function () {
  40822. this.average = 0;
  40823. this.variance = 0;
  40824. this._sampleCount = 0;
  40825. this._pos = 0;
  40826. this._m2 = 0;
  40827. };
  40828. /**
  40829. * Wraps a value around the sample range boundaries
  40830. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  40831. * @return Wrapped position in sample range
  40832. */
  40833. RollingAverage.prototype._wrapPosition = function (i) {
  40834. var max = this._samples.length;
  40835. return ((i % max) + max) % max;
  40836. };
  40837. return RollingAverage;
  40838. }());
  40839. BABYLON.RollingAverage = RollingAverage;
  40840. })(BABYLON || (BABYLON = {}));
  40841. //# sourceMappingURL=babylon.performanceMonitor.js.map
  40842. var BABYLON;
  40843. (function (BABYLON) {
  40844. /**
  40845. * This groups together the common properties used for image processing either in direct forward pass
  40846. * or through post processing effect depending on the use of the image processing pipeline in your scene
  40847. * or not.
  40848. */
  40849. var ImageProcessingConfiguration = /** @class */ (function () {
  40850. function ImageProcessingConfiguration() {
  40851. /**
  40852. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  40853. */
  40854. this.colorCurves = new BABYLON.ColorCurves();
  40855. this._colorCurvesEnabled = false;
  40856. this._colorGradingEnabled = false;
  40857. this._colorGradingWithGreenDepth = true;
  40858. this._colorGradingBGR = true;
  40859. this._exposure = 1.0;
  40860. this._toneMappingEnabled = false;
  40861. this._contrast = 1.0;
  40862. /**
  40863. * Vignette stretch size.
  40864. */
  40865. this.vignetteStretch = 0;
  40866. /**
  40867. * Vignette centre X Offset.
  40868. */
  40869. this.vignetteCentreX = 0;
  40870. /**
  40871. * Vignette centre Y Offset.
  40872. */
  40873. this.vignetteCentreY = 0;
  40874. /**
  40875. * Vignette weight or intensity of the vignette effect.
  40876. */
  40877. this.vignetteWeight = 1.5;
  40878. /**
  40879. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  40880. * if vignetteEnabled is set to true.
  40881. */
  40882. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  40883. /**
  40884. * Camera field of view used by the Vignette effect.
  40885. */
  40886. this.vignetteCameraFov = 0.5;
  40887. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  40888. this._vignetteEnabled = false;
  40889. this._applyByPostProcess = false;
  40890. this._isEnabled = true;
  40891. /**
  40892. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  40893. */
  40894. this.onUpdateParameters = new BABYLON.Observable();
  40895. }
  40896. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  40897. /**
  40898. * Gets wether the color curves effect is enabled.
  40899. */
  40900. get: function () {
  40901. return this._colorCurvesEnabled;
  40902. },
  40903. /**
  40904. * Sets wether the color curves effect is enabled.
  40905. */
  40906. set: function (value) {
  40907. if (this._colorCurvesEnabled === value) {
  40908. return;
  40909. }
  40910. this._colorCurvesEnabled = value;
  40911. this._updateParameters();
  40912. },
  40913. enumerable: true,
  40914. configurable: true
  40915. });
  40916. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  40917. /**
  40918. * Gets wether the color grading effect is enabled.
  40919. */
  40920. get: function () {
  40921. return this._colorGradingEnabled;
  40922. },
  40923. /**
  40924. * Sets wether the color grading effect is enabled.
  40925. */
  40926. set: function (value) {
  40927. if (this._colorGradingEnabled === value) {
  40928. return;
  40929. }
  40930. this._colorGradingEnabled = value;
  40931. this._updateParameters();
  40932. },
  40933. enumerable: true,
  40934. configurable: true
  40935. });
  40936. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  40937. /**
  40938. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  40939. */
  40940. get: function () {
  40941. return this._colorGradingWithGreenDepth;
  40942. },
  40943. /**
  40944. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  40945. */
  40946. set: function (value) {
  40947. if (this._colorGradingWithGreenDepth === value) {
  40948. return;
  40949. }
  40950. this._colorGradingWithGreenDepth = value;
  40951. this._updateParameters();
  40952. },
  40953. enumerable: true,
  40954. configurable: true
  40955. });
  40956. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  40957. /**
  40958. * Gets wether the color grading texture contains BGR values.
  40959. */
  40960. get: function () {
  40961. return this._colorGradingBGR;
  40962. },
  40963. /**
  40964. * Sets wether the color grading texture contains BGR values.
  40965. */
  40966. set: function (value) {
  40967. if (this._colorGradingBGR === value) {
  40968. return;
  40969. }
  40970. this._colorGradingBGR = value;
  40971. this._updateParameters();
  40972. },
  40973. enumerable: true,
  40974. configurable: true
  40975. });
  40976. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  40977. /**
  40978. * Gets the Exposure used in the effect.
  40979. */
  40980. get: function () {
  40981. return this._exposure;
  40982. },
  40983. /**
  40984. * Sets the Exposure used in the effect.
  40985. */
  40986. set: function (value) {
  40987. if (this._exposure === value) {
  40988. return;
  40989. }
  40990. this._exposure = value;
  40991. this._updateParameters();
  40992. },
  40993. enumerable: true,
  40994. configurable: true
  40995. });
  40996. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  40997. /**
  40998. * Gets wether the tone mapping effect is enabled.
  40999. */
  41000. get: function () {
  41001. return this._toneMappingEnabled;
  41002. },
  41003. /**
  41004. * Sets wether the tone mapping effect is enabled.
  41005. */
  41006. set: function (value) {
  41007. if (this._toneMappingEnabled === value) {
  41008. return;
  41009. }
  41010. this._toneMappingEnabled = value;
  41011. this._updateParameters();
  41012. },
  41013. enumerable: true,
  41014. configurable: true
  41015. });
  41016. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  41017. /**
  41018. * Gets the contrast used in the effect.
  41019. */
  41020. get: function () {
  41021. return this._contrast;
  41022. },
  41023. /**
  41024. * Sets the contrast used in the effect.
  41025. */
  41026. set: function (value) {
  41027. if (this._contrast === value) {
  41028. return;
  41029. }
  41030. this._contrast = value;
  41031. this._updateParameters();
  41032. },
  41033. enumerable: true,
  41034. configurable: true
  41035. });
  41036. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  41037. /**
  41038. * Gets the vignette blend mode allowing different kind of effect.
  41039. */
  41040. get: function () {
  41041. return this._vignetteBlendMode;
  41042. },
  41043. /**
  41044. * Sets the vignette blend mode allowing different kind of effect.
  41045. */
  41046. set: function (value) {
  41047. if (this._vignetteBlendMode === value) {
  41048. return;
  41049. }
  41050. this._vignetteBlendMode = value;
  41051. this._updateParameters();
  41052. },
  41053. enumerable: true,
  41054. configurable: true
  41055. });
  41056. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  41057. /**
  41058. * Gets wether the vignette effect is enabled.
  41059. */
  41060. get: function () {
  41061. return this._vignetteEnabled;
  41062. },
  41063. /**
  41064. * Sets wether the vignette effect is enabled.
  41065. */
  41066. set: function (value) {
  41067. if (this._vignetteEnabled === value) {
  41068. return;
  41069. }
  41070. this._vignetteEnabled = value;
  41071. this._updateParameters();
  41072. },
  41073. enumerable: true,
  41074. configurable: true
  41075. });
  41076. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  41077. /**
  41078. * Gets wether the image processing is applied through a post process or not.
  41079. */
  41080. get: function () {
  41081. return this._applyByPostProcess;
  41082. },
  41083. /**
  41084. * Sets wether the image processing is applied through a post process or not.
  41085. */
  41086. set: function (value) {
  41087. if (this._applyByPostProcess === value) {
  41088. return;
  41089. }
  41090. this._applyByPostProcess = value;
  41091. this._updateParameters();
  41092. },
  41093. enumerable: true,
  41094. configurable: true
  41095. });
  41096. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  41097. /**
  41098. * Gets wether the image processing is enabled or not.
  41099. */
  41100. get: function () {
  41101. return this._isEnabled;
  41102. },
  41103. /**
  41104. * Sets wether the image processing is enabled or not.
  41105. */
  41106. set: function (value) {
  41107. if (this._isEnabled === value) {
  41108. return;
  41109. }
  41110. this._isEnabled = value;
  41111. this._updateParameters();
  41112. },
  41113. enumerable: true,
  41114. configurable: true
  41115. });
  41116. /**
  41117. * Method called each time the image processing information changes requires to recompile the effect.
  41118. */
  41119. ImageProcessingConfiguration.prototype._updateParameters = function () {
  41120. this.onUpdateParameters.notifyObservers(this);
  41121. };
  41122. ImageProcessingConfiguration.prototype.getClassName = function () {
  41123. return "ImageProcessingConfiguration";
  41124. };
  41125. /**
  41126. * Prepare the list of uniforms associated with the Image Processing effects.
  41127. * @param uniformsList The list of uniforms used in the effect
  41128. * @param defines the list of defines currently in use
  41129. */
  41130. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  41131. if (defines.EXPOSURE) {
  41132. uniforms.push("exposureLinear");
  41133. }
  41134. if (defines.CONTRAST) {
  41135. uniforms.push("contrast");
  41136. }
  41137. if (defines.COLORGRADING) {
  41138. uniforms.push("colorTransformSettings");
  41139. }
  41140. if (defines.VIGNETTE) {
  41141. uniforms.push("vInverseScreenSize");
  41142. uniforms.push("vignetteSettings1");
  41143. uniforms.push("vignetteSettings2");
  41144. }
  41145. if (defines.COLORCURVES) {
  41146. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  41147. }
  41148. };
  41149. /**
  41150. * Prepare the list of samplers associated with the Image Processing effects.
  41151. * @param uniformsList The list of uniforms used in the effect
  41152. * @param defines the list of defines currently in use
  41153. */
  41154. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  41155. if (defines.COLORGRADING) {
  41156. samplersList.push("txColorTransform");
  41157. }
  41158. };
  41159. /**
  41160. * Prepare the list of defines associated to the shader.
  41161. * @param defines the list of defines to complete
  41162. */
  41163. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  41164. if (forPostProcess === void 0) { forPostProcess = false; }
  41165. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  41166. defines.VIGNETTE = false;
  41167. defines.TONEMAPPING = false;
  41168. defines.CONTRAST = false;
  41169. defines.EXPOSURE = false;
  41170. defines.COLORCURVES = false;
  41171. defines.COLORGRADING = false;
  41172. defines.COLORGRADING3D = false;
  41173. defines.IMAGEPROCESSING = false;
  41174. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  41175. return;
  41176. }
  41177. defines.VIGNETTE = this.vignetteEnabled;
  41178. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  41179. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  41180. defines.TONEMAPPING = this.toneMappingEnabled;
  41181. defines.CONTRAST = (this.contrast !== 1.0);
  41182. defines.EXPOSURE = (this.exposure !== 1.0);
  41183. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  41184. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  41185. if (defines.COLORGRADING) {
  41186. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  41187. }
  41188. else {
  41189. defines.COLORGRADING3D = false;
  41190. }
  41191. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  41192. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  41193. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  41194. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  41195. };
  41196. /**
  41197. * Returns true if all the image processing information are ready.
  41198. */
  41199. ImageProcessingConfiguration.prototype.isReady = function () {
  41200. // Color Grading texure can not be none blocking.
  41201. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  41202. };
  41203. /**
  41204. * Binds the image processing to the shader.
  41205. * @param effect The effect to bind to
  41206. */
  41207. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  41208. if (aspectRatio === void 0) { aspectRatio = 1; }
  41209. // Color Curves
  41210. if (this._colorCurvesEnabled && this.colorCurves) {
  41211. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  41212. }
  41213. // Vignette
  41214. if (this._vignetteEnabled) {
  41215. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  41216. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  41217. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  41218. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  41219. var vignetteScaleX = vignetteScaleY * aspectRatio;
  41220. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  41221. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  41222. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  41223. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  41224. var vignettePower = -2.0 * this.vignetteWeight;
  41225. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  41226. }
  41227. // Exposure
  41228. effect.setFloat("exposureLinear", this.exposure);
  41229. // Contrast
  41230. effect.setFloat("contrast", this.contrast);
  41231. // Color transform settings
  41232. if (this.colorGradingTexture) {
  41233. effect.setTexture("txColorTransform", this.colorGradingTexture);
  41234. var textureSize = this.colorGradingTexture.getSize().height;
  41235. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  41236. 0.5 / textureSize, // textureOffset
  41237. textureSize, // textureSize
  41238. this.colorGradingTexture.level // weight
  41239. );
  41240. }
  41241. };
  41242. /**
  41243. * Clones the current image processing instance.
  41244. * @return The cloned image processing
  41245. */
  41246. ImageProcessingConfiguration.prototype.clone = function () {
  41247. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  41248. };
  41249. /**
  41250. * Serializes the current image processing instance to a json representation.
  41251. * @return a JSON representation
  41252. */
  41253. ImageProcessingConfiguration.prototype.serialize = function () {
  41254. return BABYLON.SerializationHelper.Serialize(this);
  41255. };
  41256. /**
  41257. * Parses the image processing from a json representation.
  41258. * @param source the JSON source to parse
  41259. * @return The parsed image processing
  41260. */
  41261. ImageProcessingConfiguration.Parse = function (source) {
  41262. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  41263. };
  41264. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  41265. /**
  41266. * Used to apply the vignette as a mix with the pixel color.
  41267. */
  41268. get: function () {
  41269. return this._VIGNETTEMODE_MULTIPLY;
  41270. },
  41271. enumerable: true,
  41272. configurable: true
  41273. });
  41274. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  41275. /**
  41276. * Used to apply the vignette as a replacement of the pixel color.
  41277. */
  41278. get: function () {
  41279. return this._VIGNETTEMODE_OPAQUE;
  41280. },
  41281. enumerable: true,
  41282. configurable: true
  41283. });
  41284. // Static constants associated to the image processing.
  41285. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  41286. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  41287. __decorate([
  41288. BABYLON.serializeAsColorCurves()
  41289. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  41290. __decorate([
  41291. BABYLON.serialize()
  41292. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  41293. __decorate([
  41294. BABYLON.serializeAsTexture()
  41295. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  41296. __decorate([
  41297. BABYLON.serialize()
  41298. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  41299. __decorate([
  41300. BABYLON.serialize()
  41301. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  41302. __decorate([
  41303. BABYLON.serialize()
  41304. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  41305. __decorate([
  41306. BABYLON.serialize()
  41307. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  41308. __decorate([
  41309. BABYLON.serialize()
  41310. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  41311. __decorate([
  41312. BABYLON.serialize()
  41313. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  41314. __decorate([
  41315. BABYLON.serialize()
  41316. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  41317. __decorate([
  41318. BABYLON.serialize()
  41319. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  41320. __decorate([
  41321. BABYLON.serialize()
  41322. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  41323. __decorate([
  41324. BABYLON.serialize()
  41325. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  41326. __decorate([
  41327. BABYLON.serializeAsColor4()
  41328. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  41329. __decorate([
  41330. BABYLON.serialize()
  41331. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  41332. __decorate([
  41333. BABYLON.serialize()
  41334. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  41335. __decorate([
  41336. BABYLON.serialize()
  41337. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  41338. __decorate([
  41339. BABYLON.serialize()
  41340. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  41341. __decorate([
  41342. BABYLON.serialize()
  41343. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  41344. return ImageProcessingConfiguration;
  41345. }());
  41346. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  41347. })(BABYLON || (BABYLON = {}));
  41348. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  41349. var BABYLON;
  41350. (function (BABYLON) {
  41351. /**
  41352. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  41353. * It can help converting any input color in a desired output one. This can then be used to create effects
  41354. * from sepia, black and white to sixties or futuristic rendering...
  41355. *
  41356. * The only supported format is currently 3dl.
  41357. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  41358. */
  41359. var ColorGradingTexture = /** @class */ (function (_super) {
  41360. __extends(ColorGradingTexture, _super);
  41361. /**
  41362. * Instantiates a ColorGradingTexture from the following parameters.
  41363. *
  41364. * @param url The location of the color gradind data (currently only supporting 3dl)
  41365. * @param scene The scene the texture will be used in
  41366. */
  41367. function ColorGradingTexture(url, scene) {
  41368. var _this = _super.call(this, scene) || this;
  41369. if (!url) {
  41370. return _this;
  41371. }
  41372. _this._engine = scene.getEngine();
  41373. _this._textureMatrix = BABYLON.Matrix.Identity();
  41374. _this.name = url;
  41375. _this.url = url;
  41376. _this.hasAlpha = false;
  41377. _this.isCube = false;
  41378. _this.is3D = _this._engine.webGLVersion > 1;
  41379. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41380. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41381. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41382. _this.anisotropicFilteringLevel = 1;
  41383. _this._texture = _this._getFromCache(url, true);
  41384. if (!_this._texture) {
  41385. if (!scene.useDelayedTextureLoading) {
  41386. _this.loadTexture();
  41387. }
  41388. else {
  41389. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  41390. }
  41391. }
  41392. return _this;
  41393. }
  41394. /**
  41395. * Returns the texture matrix used in most of the material.
  41396. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  41397. */
  41398. ColorGradingTexture.prototype.getTextureMatrix = function () {
  41399. return this._textureMatrix;
  41400. };
  41401. /**
  41402. * Occurs when the file being loaded is a .3dl LUT file.
  41403. */
  41404. ColorGradingTexture.prototype.load3dlTexture = function () {
  41405. var engine = this._engine;
  41406. var texture;
  41407. if (engine.webGLVersion === 1) {
  41408. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41409. }
  41410. else {
  41411. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41412. }
  41413. this._texture = texture;
  41414. var callback = function (text) {
  41415. if (typeof text !== "string") {
  41416. return;
  41417. }
  41418. var data = null;
  41419. var tempData = null;
  41420. var line;
  41421. var lines = text.split('\n');
  41422. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  41423. var maxColor = 0;
  41424. for (var i = 0; i < lines.length; i++) {
  41425. line = lines[i];
  41426. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  41427. continue;
  41428. if (line.indexOf('#') === 0)
  41429. continue;
  41430. var words = line.split(" ");
  41431. if (size === 0) {
  41432. // Number of space + one
  41433. size = words.length;
  41434. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  41435. tempData = new Float32Array(size * size * size * 4);
  41436. continue;
  41437. }
  41438. if (size != 0) {
  41439. var r = Math.max(parseInt(words[0]), 0);
  41440. var g = Math.max(parseInt(words[1]), 0);
  41441. var b = Math.max(parseInt(words[2]), 0);
  41442. maxColor = Math.max(r, maxColor);
  41443. maxColor = Math.max(g, maxColor);
  41444. maxColor = Math.max(b, maxColor);
  41445. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  41446. if (tempData) {
  41447. tempData[pixelStorageIndex + 0] = r;
  41448. tempData[pixelStorageIndex + 1] = g;
  41449. tempData[pixelStorageIndex + 2] = b;
  41450. }
  41451. pixelIndexSlice++;
  41452. if (pixelIndexSlice % size == 0) {
  41453. pixelIndexH++;
  41454. pixelIndexSlice = 0;
  41455. if (pixelIndexH % size == 0) {
  41456. pixelIndexW++;
  41457. pixelIndexH = 0;
  41458. }
  41459. }
  41460. }
  41461. }
  41462. if (tempData && data) {
  41463. for (var i = 0; i < tempData.length; i++) {
  41464. if (i > 0 && (i + 1) % 4 === 0) {
  41465. data[i] = 255;
  41466. }
  41467. else {
  41468. var value = tempData[i];
  41469. data[i] = (value / maxColor * 255);
  41470. }
  41471. }
  41472. }
  41473. if (texture.is3D) {
  41474. texture.updateSize(size, size, size);
  41475. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41476. }
  41477. else {
  41478. texture.updateSize(size * size, size);
  41479. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41480. }
  41481. };
  41482. var scene = this.getScene();
  41483. if (scene) {
  41484. scene._loadFile(this.url, callback);
  41485. }
  41486. else {
  41487. this._engine._loadFile(this.url, callback);
  41488. }
  41489. return this._texture;
  41490. };
  41491. /**
  41492. * Starts the loading process of the texture.
  41493. */
  41494. ColorGradingTexture.prototype.loadTexture = function () {
  41495. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  41496. this.load3dlTexture();
  41497. }
  41498. };
  41499. /**
  41500. * Clones the color gradind texture.
  41501. */
  41502. ColorGradingTexture.prototype.clone = function () {
  41503. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  41504. // Base texture
  41505. newTexture.level = this.level;
  41506. return newTexture;
  41507. };
  41508. /**
  41509. * Called during delayed load for textures.
  41510. */
  41511. ColorGradingTexture.prototype.delayLoad = function () {
  41512. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  41513. return;
  41514. }
  41515. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  41516. this._texture = this._getFromCache(this.url, true);
  41517. if (!this._texture) {
  41518. this.loadTexture();
  41519. }
  41520. };
  41521. /**
  41522. * Parses a color grading texture serialized by Babylon.
  41523. * @param parsedTexture The texture information being parsedTexture
  41524. * @param scene The scene to load the texture in
  41525. * @param rootUrl The root url of the data assets to load
  41526. * @return A color gradind texture
  41527. */
  41528. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  41529. var texture = null;
  41530. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  41531. texture = new ColorGradingTexture(parsedTexture.name, scene);
  41532. texture.name = parsedTexture.name;
  41533. texture.level = parsedTexture.level;
  41534. }
  41535. return texture;
  41536. };
  41537. /**
  41538. * Serializes the LUT texture to json format.
  41539. */
  41540. ColorGradingTexture.prototype.serialize = function () {
  41541. if (!this.name) {
  41542. return null;
  41543. }
  41544. var serializationObject = {};
  41545. serializationObject.name = this.name;
  41546. serializationObject.level = this.level;
  41547. serializationObject.customType = "BABYLON.ColorGradingTexture";
  41548. return serializationObject;
  41549. };
  41550. /**
  41551. * Empty line regex stored for GC.
  41552. */
  41553. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  41554. return ColorGradingTexture;
  41555. }(BABYLON.BaseTexture));
  41556. BABYLON.ColorGradingTexture = ColorGradingTexture;
  41557. })(BABYLON || (BABYLON = {}));
  41558. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  41559. var BABYLON;
  41560. (function (BABYLON) {
  41561. /**
  41562. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41563. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41564. * 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;
  41565. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41566. */
  41567. var ColorCurves = /** @class */ (function () {
  41568. function ColorCurves() {
  41569. this._dirty = true;
  41570. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  41571. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  41572. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41573. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  41574. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41575. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  41576. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  41577. this._globalHue = 30;
  41578. this._globalDensity = 0;
  41579. this._globalSaturation = 0;
  41580. this._globalExposure = 0;
  41581. this._highlightsHue = 30;
  41582. this._highlightsDensity = 0;
  41583. this._highlightsSaturation = 0;
  41584. this._highlightsExposure = 0;
  41585. this._midtonesHue = 30;
  41586. this._midtonesDensity = 0;
  41587. this._midtonesSaturation = 0;
  41588. this._midtonesExposure = 0;
  41589. this._shadowsHue = 30;
  41590. this._shadowsDensity = 0;
  41591. this._shadowsSaturation = 0;
  41592. this._shadowsExposure = 0;
  41593. }
  41594. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  41595. /**
  41596. * Gets the global Hue value.
  41597. * 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).
  41598. */
  41599. get: function () {
  41600. return this._globalHue;
  41601. },
  41602. /**
  41603. * Sets the global Hue value.
  41604. * 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).
  41605. */
  41606. set: function (value) {
  41607. this._globalHue = value;
  41608. this._dirty = true;
  41609. },
  41610. enumerable: true,
  41611. configurable: true
  41612. });
  41613. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  41614. /**
  41615. * Gets the global Density value.
  41616. * 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.
  41617. * Values less than zero provide a filter of opposite hue.
  41618. */
  41619. get: function () {
  41620. return this._globalDensity;
  41621. },
  41622. /**
  41623. * Sets the global Density value.
  41624. * 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.
  41625. * Values less than zero provide a filter of opposite hue.
  41626. */
  41627. set: function (value) {
  41628. this._globalDensity = value;
  41629. this._dirty = true;
  41630. },
  41631. enumerable: true,
  41632. configurable: true
  41633. });
  41634. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  41635. /**
  41636. * Gets the global Saturation value.
  41637. * 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.
  41638. */
  41639. get: function () {
  41640. return this._globalSaturation;
  41641. },
  41642. /**
  41643. * Sets the global Saturation value.
  41644. * 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.
  41645. */
  41646. set: function (value) {
  41647. this._globalSaturation = value;
  41648. this._dirty = true;
  41649. },
  41650. enumerable: true,
  41651. configurable: true
  41652. });
  41653. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  41654. /**
  41655. * Gets the highlights Hue value.
  41656. * 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).
  41657. */
  41658. get: function () {
  41659. return this._highlightsHue;
  41660. },
  41661. /**
  41662. * Sets the highlights Hue value.
  41663. * 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).
  41664. */
  41665. set: function (value) {
  41666. this._highlightsHue = value;
  41667. this._dirty = true;
  41668. },
  41669. enumerable: true,
  41670. configurable: true
  41671. });
  41672. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  41673. /**
  41674. * Gets the highlights Density value.
  41675. * 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.
  41676. * Values less than zero provide a filter of opposite hue.
  41677. */
  41678. get: function () {
  41679. return this._highlightsDensity;
  41680. },
  41681. /**
  41682. * Sets the highlights Density value.
  41683. * 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.
  41684. * Values less than zero provide a filter of opposite hue.
  41685. */
  41686. set: function (value) {
  41687. this._highlightsDensity = value;
  41688. this._dirty = true;
  41689. },
  41690. enumerable: true,
  41691. configurable: true
  41692. });
  41693. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  41694. /**
  41695. * Gets the highlights Saturation value.
  41696. * 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.
  41697. */
  41698. get: function () {
  41699. return this._highlightsSaturation;
  41700. },
  41701. /**
  41702. * Sets the highlights Saturation value.
  41703. * 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.
  41704. */
  41705. set: function (value) {
  41706. this._highlightsSaturation = value;
  41707. this._dirty = true;
  41708. },
  41709. enumerable: true,
  41710. configurable: true
  41711. });
  41712. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  41713. /**
  41714. * Gets the highlights Exposure value.
  41715. * 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.
  41716. */
  41717. get: function () {
  41718. return this._highlightsExposure;
  41719. },
  41720. /**
  41721. * Sets the highlights Exposure value.
  41722. * 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.
  41723. */
  41724. set: function (value) {
  41725. this._highlightsExposure = value;
  41726. this._dirty = true;
  41727. },
  41728. enumerable: true,
  41729. configurable: true
  41730. });
  41731. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  41732. /**
  41733. * Gets the midtones Hue value.
  41734. * 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).
  41735. */
  41736. get: function () {
  41737. return this._midtonesHue;
  41738. },
  41739. /**
  41740. * Sets the midtones Hue value.
  41741. * 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).
  41742. */
  41743. set: function (value) {
  41744. this._midtonesHue = value;
  41745. this._dirty = true;
  41746. },
  41747. enumerable: true,
  41748. configurable: true
  41749. });
  41750. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  41751. /**
  41752. * Gets the midtones Density value.
  41753. * 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.
  41754. * Values less than zero provide a filter of opposite hue.
  41755. */
  41756. get: function () {
  41757. return this._midtonesDensity;
  41758. },
  41759. /**
  41760. * Sets the midtones Density value.
  41761. * 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.
  41762. * Values less than zero provide a filter of opposite hue.
  41763. */
  41764. set: function (value) {
  41765. this._midtonesDensity = value;
  41766. this._dirty = true;
  41767. },
  41768. enumerable: true,
  41769. configurable: true
  41770. });
  41771. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  41772. /**
  41773. * Gets the midtones Saturation value.
  41774. * 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.
  41775. */
  41776. get: function () {
  41777. return this._midtonesSaturation;
  41778. },
  41779. /**
  41780. * Sets the midtones Saturation value.
  41781. * 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.
  41782. */
  41783. set: function (value) {
  41784. this._midtonesSaturation = value;
  41785. this._dirty = true;
  41786. },
  41787. enumerable: true,
  41788. configurable: true
  41789. });
  41790. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  41791. /**
  41792. * Gets the midtones Exposure value.
  41793. * 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.
  41794. */
  41795. get: function () {
  41796. return this._midtonesExposure;
  41797. },
  41798. /**
  41799. * Sets the midtones Exposure value.
  41800. * 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.
  41801. */
  41802. set: function (value) {
  41803. this._midtonesExposure = value;
  41804. this._dirty = true;
  41805. },
  41806. enumerable: true,
  41807. configurable: true
  41808. });
  41809. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  41810. /**
  41811. * Gets the shadows Hue value.
  41812. * 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).
  41813. */
  41814. get: function () {
  41815. return this._shadowsHue;
  41816. },
  41817. /**
  41818. * Sets the shadows Hue value.
  41819. * 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).
  41820. */
  41821. set: function (value) {
  41822. this._shadowsHue = value;
  41823. this._dirty = true;
  41824. },
  41825. enumerable: true,
  41826. configurable: true
  41827. });
  41828. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  41829. /**
  41830. * Gets the shadows Density value.
  41831. * 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.
  41832. * Values less than zero provide a filter of opposite hue.
  41833. */
  41834. get: function () {
  41835. return this._shadowsDensity;
  41836. },
  41837. /**
  41838. * Sets the shadows Density value.
  41839. * 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.
  41840. * Values less than zero provide a filter of opposite hue.
  41841. */
  41842. set: function (value) {
  41843. this._shadowsDensity = value;
  41844. this._dirty = true;
  41845. },
  41846. enumerable: true,
  41847. configurable: true
  41848. });
  41849. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  41850. /**
  41851. * Gets the shadows Saturation value.
  41852. * 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.
  41853. */
  41854. get: function () {
  41855. return this._shadowsSaturation;
  41856. },
  41857. /**
  41858. * Sets the shadows Saturation value.
  41859. * 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.
  41860. */
  41861. set: function (value) {
  41862. this._shadowsSaturation = value;
  41863. this._dirty = true;
  41864. },
  41865. enumerable: true,
  41866. configurable: true
  41867. });
  41868. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  41869. /**
  41870. * Gets the shadows Exposure value.
  41871. * 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.
  41872. */
  41873. get: function () {
  41874. return this._shadowsExposure;
  41875. },
  41876. /**
  41877. * Sets the shadows Exposure value.
  41878. * 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.
  41879. */
  41880. set: function (value) {
  41881. this._shadowsExposure = value;
  41882. this._dirty = true;
  41883. },
  41884. enumerable: true,
  41885. configurable: true
  41886. });
  41887. ColorCurves.prototype.getClassName = function () {
  41888. return "ColorCurves";
  41889. };
  41890. /**
  41891. * Binds the color curves to the shader.
  41892. * @param colorCurves The color curve to bind
  41893. * @param effect The effect to bind to
  41894. */
  41895. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  41896. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  41897. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  41898. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  41899. if (colorCurves._dirty) {
  41900. colorCurves._dirty = false;
  41901. // Fill in global info.
  41902. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  41903. // Compute highlights info.
  41904. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  41905. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  41906. // Compute midtones info.
  41907. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  41908. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  41909. // Compute shadows info.
  41910. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  41911. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  41912. // Compute deltas (neutral is midtones).
  41913. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  41914. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  41915. }
  41916. if (effect) {
  41917. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  41918. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  41919. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  41920. }
  41921. };
  41922. /**
  41923. * Prepare the list of uniforms associated with the ColorCurves effects.
  41924. * @param uniformsList The list of uniforms used in the effect
  41925. */
  41926. ColorCurves.PrepareUniforms = function (uniformsList) {
  41927. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  41928. };
  41929. /**
  41930. * Returns color grading data based on a hue, density, saturation and exposure value.
  41931. * @param filterHue The hue of the color filter.
  41932. * @param filterDensity The density of the color filter.
  41933. * @param saturation The saturation.
  41934. * @param exposure The exposure.
  41935. * @param result The result data container.
  41936. */
  41937. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  41938. if (hue == null) {
  41939. return;
  41940. }
  41941. hue = ColorCurves.clamp(hue, 0, 360);
  41942. density = ColorCurves.clamp(density, -100, 100);
  41943. saturation = ColorCurves.clamp(saturation, -100, 100);
  41944. exposure = ColorCurves.clamp(exposure, -100, 100);
  41945. // Remap the slider/config filter density with non-linear mapping and also scale by half
  41946. // so that the maximum filter density is only 50% control. This provides fine control
  41947. // for small values and reasonable range.
  41948. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  41949. density *= 0.5;
  41950. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  41951. if (density < 0) {
  41952. density *= -1;
  41953. hue = (hue + 180) % 360;
  41954. }
  41955. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  41956. result.scaleToRef(2, result);
  41957. result.a = 1 + 0.01 * saturation;
  41958. };
  41959. /**
  41960. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  41961. * @param value The input slider value in range [-100,100].
  41962. * @returns Adjusted value.
  41963. */
  41964. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  41965. value /= 100;
  41966. var x = Math.abs(value);
  41967. x = Math.pow(x, 2);
  41968. if (value < 0) {
  41969. x *= -1;
  41970. }
  41971. x *= 100;
  41972. return x;
  41973. };
  41974. /**
  41975. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  41976. * @param hue The hue (H) input.
  41977. * @param saturation The saturation (S) input.
  41978. * @param brightness The brightness (B) input.
  41979. * @result An RGBA color represented as Vector4.
  41980. */
  41981. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  41982. var h = ColorCurves.clamp(hue, 0, 360);
  41983. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  41984. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  41985. if (s === 0) {
  41986. result.r = v;
  41987. result.g = v;
  41988. result.b = v;
  41989. }
  41990. else {
  41991. // sector 0 to 5
  41992. h /= 60;
  41993. var i = Math.floor(h);
  41994. // fractional part of h
  41995. var f = h - i;
  41996. var p = v * (1 - s);
  41997. var q = v * (1 - s * f);
  41998. var t = v * (1 - s * (1 - f));
  41999. switch (i) {
  42000. case 0:
  42001. result.r = v;
  42002. result.g = t;
  42003. result.b = p;
  42004. break;
  42005. case 1:
  42006. result.r = q;
  42007. result.g = v;
  42008. result.b = p;
  42009. break;
  42010. case 2:
  42011. result.r = p;
  42012. result.g = v;
  42013. result.b = t;
  42014. break;
  42015. case 3:
  42016. result.r = p;
  42017. result.g = q;
  42018. result.b = v;
  42019. break;
  42020. case 4:
  42021. result.r = t;
  42022. result.g = p;
  42023. result.b = v;
  42024. break;
  42025. default: // case 5:
  42026. result.r = v;
  42027. result.g = p;
  42028. result.b = q;
  42029. break;
  42030. }
  42031. }
  42032. result.a = 1;
  42033. };
  42034. /**
  42035. * Returns a value clamped between min and max
  42036. * @param value The value to clamp
  42037. * @param min The minimum of value
  42038. * @param max The maximum of value
  42039. * @returns The clamped value.
  42040. */
  42041. ColorCurves.clamp = function (value, min, max) {
  42042. return Math.min(Math.max(value, min), max);
  42043. };
  42044. /**
  42045. * Clones the current color curve instance.
  42046. * @return The cloned curves
  42047. */
  42048. ColorCurves.prototype.clone = function () {
  42049. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  42050. };
  42051. /**
  42052. * Serializes the current color curve instance to a json representation.
  42053. * @return a JSON representation
  42054. */
  42055. ColorCurves.prototype.serialize = function () {
  42056. return BABYLON.SerializationHelper.Serialize(this);
  42057. };
  42058. /**
  42059. * Parses the color curve from a json representation.
  42060. * @param source the JSON source to parse
  42061. * @return The parsed curves
  42062. */
  42063. ColorCurves.Parse = function (source) {
  42064. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  42065. };
  42066. __decorate([
  42067. BABYLON.serialize()
  42068. ], ColorCurves.prototype, "_globalHue", void 0);
  42069. __decorate([
  42070. BABYLON.serialize()
  42071. ], ColorCurves.prototype, "_globalDensity", void 0);
  42072. __decorate([
  42073. BABYLON.serialize()
  42074. ], ColorCurves.prototype, "_globalSaturation", void 0);
  42075. __decorate([
  42076. BABYLON.serialize()
  42077. ], ColorCurves.prototype, "_globalExposure", void 0);
  42078. __decorate([
  42079. BABYLON.serialize()
  42080. ], ColorCurves.prototype, "_highlightsHue", void 0);
  42081. __decorate([
  42082. BABYLON.serialize()
  42083. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  42084. __decorate([
  42085. BABYLON.serialize()
  42086. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  42087. __decorate([
  42088. BABYLON.serialize()
  42089. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  42090. __decorate([
  42091. BABYLON.serialize()
  42092. ], ColorCurves.prototype, "_midtonesHue", void 0);
  42093. __decorate([
  42094. BABYLON.serialize()
  42095. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  42096. __decorate([
  42097. BABYLON.serialize()
  42098. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  42099. __decorate([
  42100. BABYLON.serialize()
  42101. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  42102. return ColorCurves;
  42103. }());
  42104. BABYLON.ColorCurves = ColorCurves;
  42105. })(BABYLON || (BABYLON = {}));
  42106. //# sourceMappingURL=babylon.colorCurves.js.map
  42107. //# sourceMappingURL=babylon.behavior.js.map
  42108. var BABYLON;
  42109. (function (BABYLON) {
  42110. /**
  42111. * "Static Class" containing the most commonly used helper while dealing with material for
  42112. * rendering purpose.
  42113. *
  42114. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  42115. *
  42116. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  42117. */
  42118. var MaterialHelper = /** @class */ (function () {
  42119. function MaterialHelper() {
  42120. }
  42121. /**
  42122. * Bind the current view position to an effect.
  42123. * @param effect The effect to be bound
  42124. * @param scene The scene the eyes position is used from
  42125. */
  42126. MaterialHelper.BindEyePosition = function (effect, scene) {
  42127. if (scene._forcedViewPosition) {
  42128. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  42129. return;
  42130. }
  42131. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  42132. };
  42133. /**
  42134. * Helps preparing the defines values about the UVs in used in the effect.
  42135. * UVs are shared as much as we can accross chanels in the shaders.
  42136. * @param texture The texture we are preparing the UVs for
  42137. * @param defines The defines to update
  42138. * @param key The chanel key "diffuse", "specular"... used in the shader
  42139. */
  42140. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  42141. defines._needUVs = true;
  42142. defines[key] = true;
  42143. if (texture.getTextureMatrix().isIdentity(true)) {
  42144. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  42145. if (texture.coordinatesIndex === 0) {
  42146. defines["MAINUV1"] = true;
  42147. }
  42148. else {
  42149. defines["MAINUV2"] = true;
  42150. }
  42151. }
  42152. else {
  42153. defines[key + "DIRECTUV"] = 0;
  42154. }
  42155. };
  42156. /**
  42157. * Binds a texture matrix value to its corrsponding uniform
  42158. * @param texture The texture to bind the matrix for
  42159. * @param uniformBuffer The uniform buffer receivin the data
  42160. * @param key The chanel key "diffuse", "specular"... used in the shader
  42161. */
  42162. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  42163. var matrix = texture.getTextureMatrix();
  42164. if (!matrix.isIdentity(true)) {
  42165. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  42166. }
  42167. };
  42168. /**
  42169. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  42170. * @param mesh defines the current mesh
  42171. * @param scene defines the current scene
  42172. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  42173. * @param pointsCloud defines if point cloud rendering has to be turned on
  42174. * @param fogEnabled defines if fog has to be turned on
  42175. * @param alphaTest defines if alpha testing has to be turned on
  42176. * @param defines defines the current list of defines
  42177. */
  42178. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  42179. if (defines._areMiscDirty) {
  42180. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  42181. defines["POINTSIZE"] = pointsCloud;
  42182. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  42183. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  42184. defines["ALPHATEST"] = alphaTest;
  42185. }
  42186. };
  42187. /**
  42188. * Helper used to prepare the list of defines associated with frame values for shader compilation
  42189. * @param scene defines the current scene
  42190. * @param engine defines the current engine
  42191. * @param defines specifies the list of active defines
  42192. * @param useInstances defines if instances have to be turned on
  42193. * @param useClipPlane defines if clip plane have to be turned on
  42194. */
  42195. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  42196. if (useClipPlane === void 0) { useClipPlane = null; }
  42197. var changed = false;
  42198. if (useClipPlane == null) {
  42199. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  42200. }
  42201. if (defines["CLIPPLANE"] !== useClipPlane) {
  42202. defines["CLIPPLANE"] = useClipPlane;
  42203. changed = true;
  42204. }
  42205. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  42206. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  42207. changed = true;
  42208. }
  42209. if (defines["INSTANCES"] !== useInstances) {
  42210. defines["INSTANCES"] = useInstances;
  42211. changed = true;
  42212. }
  42213. if (changed) {
  42214. defines.markAsUnprocessed();
  42215. }
  42216. };
  42217. /**
  42218. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  42219. * @param mesh The mesh containing the geometry data we will draw
  42220. * @param defines The defines to update
  42221. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  42222. * @param useBones Precise whether bones should be used or not (override mesh info)
  42223. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  42224. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  42225. * @returns false if defines are considered not dirty and have not been checked
  42226. */
  42227. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  42228. if (useMorphTargets === void 0) { useMorphTargets = false; }
  42229. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  42230. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  42231. return false;
  42232. }
  42233. defines._normals = defines._needNormals;
  42234. defines._uvs = defines._needUVs;
  42235. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  42236. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  42237. defines["TANGENT"] = true;
  42238. }
  42239. if (defines._needUVs) {
  42240. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  42241. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  42242. }
  42243. else {
  42244. defines["UV1"] = false;
  42245. defines["UV2"] = false;
  42246. }
  42247. if (useVertexColor) {
  42248. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  42249. defines["VERTEXCOLOR"] = hasVertexColors;
  42250. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  42251. }
  42252. if (useBones) {
  42253. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42254. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  42255. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  42256. }
  42257. else {
  42258. defines["NUM_BONE_INFLUENCERS"] = 0;
  42259. defines["BonesPerMesh"] = 0;
  42260. }
  42261. }
  42262. if (useMorphTargets) {
  42263. var manager = mesh.morphTargetManager;
  42264. if (manager) {
  42265. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  42266. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  42267. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  42268. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  42269. }
  42270. else {
  42271. defines["MORPHTARGETS_TANGENT"] = false;
  42272. defines["MORPHTARGETS_NORMAL"] = false;
  42273. defines["MORPHTARGETS"] = false;
  42274. defines["NUM_MORPH_INFLUENCERS"] = 0;
  42275. }
  42276. }
  42277. return true;
  42278. };
  42279. /**
  42280. * Prepares the defines related to the light information passed in parameter
  42281. * @param scene The scene we are intending to draw
  42282. * @param mesh The mesh the effect is compiling for
  42283. * @param defines The defines to update
  42284. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  42285. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  42286. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  42287. * @returns true if normals will be required for the rest of the effect
  42288. */
  42289. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  42290. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42291. if (disableLighting === void 0) { disableLighting = false; }
  42292. if (!defines._areLightsDirty) {
  42293. return defines._needNormals;
  42294. }
  42295. var lightIndex = 0;
  42296. var needNormals = false;
  42297. var needRebuild = false;
  42298. var lightmapMode = false;
  42299. var shadowEnabled = false;
  42300. var specularEnabled = false;
  42301. if (scene.lightsEnabled && !disableLighting) {
  42302. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  42303. var light = _a[_i];
  42304. needNormals = true;
  42305. if (defines["LIGHT" + lightIndex] === undefined) {
  42306. needRebuild = true;
  42307. }
  42308. defines["LIGHT" + lightIndex] = true;
  42309. defines["SPOTLIGHT" + lightIndex] = false;
  42310. defines["HEMILIGHT" + lightIndex] = false;
  42311. defines["POINTLIGHT" + lightIndex] = false;
  42312. defines["DIRLIGHT" + lightIndex] = false;
  42313. var type;
  42314. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  42315. type = "SPOTLIGHT" + lightIndex;
  42316. var spotLight = light;
  42317. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? true : false;
  42318. }
  42319. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  42320. type = "HEMILIGHT" + lightIndex;
  42321. }
  42322. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  42323. type = "POINTLIGHT" + lightIndex;
  42324. }
  42325. else {
  42326. type = "DIRLIGHT" + lightIndex;
  42327. }
  42328. defines[type] = true;
  42329. // Specular
  42330. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  42331. specularEnabled = true;
  42332. }
  42333. // Shadows
  42334. defines["SHADOW" + lightIndex] = false;
  42335. defines["SHADOWPCF" + lightIndex] = false;
  42336. defines["SHADOWPCSS" + lightIndex] = false;
  42337. defines["SHADOWPOISSON" + lightIndex] = false;
  42338. defines["SHADOWESM" + lightIndex] = false;
  42339. defines["SHADOWCUBE" + lightIndex] = false;
  42340. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  42341. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  42342. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  42343. var shadowGenerator = light.getShadowGenerator();
  42344. if (shadowGenerator) {
  42345. shadowEnabled = true;
  42346. shadowGenerator.prepareDefines(defines, lightIndex);
  42347. }
  42348. }
  42349. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  42350. lightmapMode = true;
  42351. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  42352. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  42353. }
  42354. else {
  42355. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  42356. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  42357. }
  42358. lightIndex++;
  42359. if (lightIndex === maxSimultaneousLights)
  42360. break;
  42361. }
  42362. }
  42363. defines["SPECULARTERM"] = specularEnabled;
  42364. defines["SHADOWS"] = shadowEnabled;
  42365. // Resetting all other lights if any
  42366. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  42367. if (defines["LIGHT" + index] !== undefined) {
  42368. defines["LIGHT" + index] = false;
  42369. defines["HEMILIGHT" + lightIndex] = false;
  42370. defines["POINTLIGHT" + lightIndex] = false;
  42371. defines["DIRLIGHT" + lightIndex] = false;
  42372. defines["SPOTLIGHT" + lightIndex] = false;
  42373. defines["SHADOW" + lightIndex] = false;
  42374. }
  42375. }
  42376. var caps = scene.getEngine().getCaps();
  42377. if (defines["SHADOWFLOAT"] === undefined) {
  42378. needRebuild = true;
  42379. }
  42380. defines["SHADOWFLOAT"] = shadowEnabled &&
  42381. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  42382. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  42383. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  42384. if (needRebuild) {
  42385. defines.rebuild();
  42386. }
  42387. return needNormals;
  42388. };
  42389. /**
  42390. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  42391. * that won t be acctive due to defines being turned off.
  42392. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  42393. * @param samplersList The samplers list
  42394. * @param defines The defines helping in the list generation
  42395. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  42396. */
  42397. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  42398. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42399. var uniformsList;
  42400. var uniformBuffersList = null;
  42401. if (uniformsListOrOptions.uniformsNames) {
  42402. var options = uniformsListOrOptions;
  42403. uniformsList = options.uniformsNames;
  42404. uniformBuffersList = options.uniformBuffersNames;
  42405. samplersList = options.samplers;
  42406. defines = options.defines;
  42407. maxSimultaneousLights = options.maxSimultaneousLights;
  42408. }
  42409. else {
  42410. uniformsList = uniformsListOrOptions;
  42411. if (!samplersList) {
  42412. samplersList = [];
  42413. }
  42414. }
  42415. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42416. if (!defines["LIGHT" + lightIndex]) {
  42417. break;
  42418. }
  42419. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  42420. if (uniformBuffersList) {
  42421. uniformBuffersList.push("Light" + lightIndex);
  42422. }
  42423. samplersList.push("shadowSampler" + lightIndex);
  42424. samplersList.push("depthSampler" + lightIndex);
  42425. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  42426. samplersList.push("projectionLightSampler" + lightIndex);
  42427. uniformsList.push("textureProjectionMatrix" + lightIndex);
  42428. }
  42429. }
  42430. if (defines["NUM_MORPH_INFLUENCERS"]) {
  42431. uniformsList.push("morphTargetInfluences");
  42432. }
  42433. };
  42434. /**
  42435. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  42436. * @param defines The defines to update while falling back
  42437. * @param fallbacks The authorized effect fallbacks
  42438. * @param maxSimultaneousLights The maximum number of lights allowed
  42439. * @param rank the current rank of the Effect
  42440. * @returns The newly affected rank
  42441. */
  42442. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  42443. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42444. if (rank === void 0) { rank = 0; }
  42445. var lightFallbackRank = 0;
  42446. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42447. if (!defines["LIGHT" + lightIndex]) {
  42448. break;
  42449. }
  42450. if (lightIndex > 0) {
  42451. lightFallbackRank = rank + lightIndex;
  42452. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  42453. }
  42454. if (!defines["SHADOWS"]) {
  42455. if (defines["SHADOW" + lightIndex]) {
  42456. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  42457. }
  42458. if (defines["SHADOWPCF" + lightIndex]) {
  42459. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  42460. }
  42461. if (defines["SHADOWPCSS" + lightIndex]) {
  42462. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  42463. }
  42464. if (defines["SHADOWPOISSON" + lightIndex]) {
  42465. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  42466. }
  42467. if (defines["SHADOWESM" + lightIndex]) {
  42468. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  42469. }
  42470. }
  42471. }
  42472. return lightFallbackRank++;
  42473. };
  42474. /**
  42475. * Prepares the list of attributes required for morph targets according to the effect defines.
  42476. * @param attribs The current list of supported attribs
  42477. * @param mesh The mesh to prepare the morph targets attributes for
  42478. * @param defines The current Defines of the effect
  42479. */
  42480. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  42481. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  42482. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  42483. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  42484. var manager = mesh.morphTargetManager;
  42485. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  42486. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  42487. for (var index = 0; index < influencers; index++) {
  42488. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  42489. if (normal) {
  42490. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  42491. }
  42492. if (tangent) {
  42493. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  42494. }
  42495. if (attribs.length > maxAttributesCount) {
  42496. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  42497. }
  42498. }
  42499. }
  42500. };
  42501. /**
  42502. * Prepares the list of attributes required for bones according to the effect defines.
  42503. * @param attribs The current list of supported attribs
  42504. * @param mesh The mesh to prepare the bones attributes for
  42505. * @param defines The current Defines of the effect
  42506. * @param fallbacks The current efffect fallback strategy
  42507. */
  42508. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  42509. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  42510. fallbacks.addCPUSkinningFallback(0, mesh);
  42511. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  42512. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  42513. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  42514. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  42515. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  42516. }
  42517. }
  42518. };
  42519. /**
  42520. * Prepares the list of attributes required for instances according to the effect defines.
  42521. * @param attribs The current list of supported attribs
  42522. * @param defines The current Defines of the effect
  42523. */
  42524. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  42525. if (defines["INSTANCES"]) {
  42526. attribs.push("world0");
  42527. attribs.push("world1");
  42528. attribs.push("world2");
  42529. attribs.push("world3");
  42530. }
  42531. };
  42532. /**
  42533. * Binds the light shadow information to the effect for the given mesh.
  42534. * @param light The light containing the generator
  42535. * @param scene The scene the lights belongs to
  42536. * @param mesh The mesh we are binding the information to render
  42537. * @param lightIndex The light index in the effect used to render the mesh
  42538. * @param effect The effect we are binding the data to
  42539. */
  42540. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  42541. if (light.shadowEnabled && mesh.receiveShadows) {
  42542. var shadowGenerator = light.getShadowGenerator();
  42543. if (shadowGenerator) {
  42544. shadowGenerator.bindShadowLight(lightIndex, effect);
  42545. }
  42546. }
  42547. };
  42548. /**
  42549. * Binds the light information to the effect.
  42550. * @param light The light containing the generator
  42551. * @param effect The effect we are binding the data to
  42552. * @param lightIndex The light index in the effect used to render
  42553. */
  42554. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  42555. light.transferToEffect(effect, lightIndex + "");
  42556. };
  42557. /**
  42558. * Binds the lights information from the scene to the effect for the given mesh.
  42559. * @param scene The scene the lights belongs to
  42560. * @param mesh The mesh we are binding the information to render
  42561. * @param effect The effect we are binding the data to
  42562. * @param defines The generated defines for the effect
  42563. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  42564. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  42565. */
  42566. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  42567. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42568. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  42569. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  42570. for (var i = 0; i < len; i++) {
  42571. var light = mesh._lightSources[i];
  42572. var iAsString = i.toString();
  42573. var scaledIntensity = light.getScaledIntensity();
  42574. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  42575. MaterialHelper.BindLightProperties(light, effect, i);
  42576. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  42577. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  42578. if (defines["SPECULARTERM"]) {
  42579. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  42580. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  42581. }
  42582. // Shadows
  42583. if (scene.shadowsEnabled) {
  42584. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  42585. }
  42586. light._uniformBuffer.update();
  42587. }
  42588. };
  42589. /**
  42590. * Binds the fog information from the scene to the effect for the given mesh.
  42591. * @param scene The scene the lights belongs to
  42592. * @param mesh The mesh we are binding the information to render
  42593. * @param effect The effect we are binding the data to
  42594. */
  42595. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  42596. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  42597. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  42598. effect.setColor3("vFogColor", scene.fogColor);
  42599. }
  42600. };
  42601. /**
  42602. * Binds the bones information from the mesh to the effect.
  42603. * @param mesh The mesh we are binding the information to render
  42604. * @param effect The effect we are binding the data to
  42605. */
  42606. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  42607. if (!effect || !mesh) {
  42608. return;
  42609. }
  42610. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  42611. mesh.computeBonesUsingShaders = false;
  42612. }
  42613. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42614. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  42615. if (matrices) {
  42616. effect.setMatrices("mBones", matrices);
  42617. }
  42618. }
  42619. };
  42620. /**
  42621. * Binds the morph targets information from the mesh to the effect.
  42622. * @param abstractMesh The mesh we are binding the information to render
  42623. * @param effect The effect we are binding the data to
  42624. */
  42625. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  42626. var manager = abstractMesh.morphTargetManager;
  42627. if (!abstractMesh || !manager) {
  42628. return;
  42629. }
  42630. effect.setFloatArray("morphTargetInfluences", manager.influences);
  42631. };
  42632. /**
  42633. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  42634. * @param defines The generated defines used in the effect
  42635. * @param effect The effect we are binding the data to
  42636. * @param scene The scene we are willing to render with logarithmic scale for
  42637. */
  42638. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  42639. if (defines["LOGARITHMICDEPTH"]) {
  42640. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  42641. }
  42642. };
  42643. /**
  42644. * Binds the clip plane information from the scene to the effect.
  42645. * @param scene The scene the clip plane information are extracted from
  42646. * @param effect The effect we are binding the data to
  42647. */
  42648. MaterialHelper.BindClipPlane = function (effect, scene) {
  42649. if (scene.clipPlane) {
  42650. var clipPlane = scene.clipPlane;
  42651. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  42652. }
  42653. };
  42654. return MaterialHelper;
  42655. }());
  42656. BABYLON.MaterialHelper = MaterialHelper;
  42657. })(BABYLON || (BABYLON = {}));
  42658. //# sourceMappingURL=babylon.materialHelper.js.map
  42659. var BABYLON;
  42660. (function (BABYLON) {
  42661. var PushMaterial = /** @class */ (function (_super) {
  42662. __extends(PushMaterial, _super);
  42663. function PushMaterial(name, scene) {
  42664. var _this = _super.call(this, name, scene) || this;
  42665. _this._normalMatrix = new BABYLON.Matrix();
  42666. _this.storeEffectOnSubMeshes = true;
  42667. return _this;
  42668. }
  42669. PushMaterial.prototype.getEffect = function () {
  42670. return this._activeEffect;
  42671. };
  42672. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  42673. if (!mesh) {
  42674. return false;
  42675. }
  42676. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  42677. return true;
  42678. }
  42679. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  42680. };
  42681. /**
  42682. * Binds the given world matrix to the active effect
  42683. *
  42684. * @param world the matrix to bind
  42685. */
  42686. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  42687. this._activeEffect.setMatrix("world", world);
  42688. };
  42689. /**
  42690. * Binds the given normal matrix to the active effect
  42691. *
  42692. * @param normalMatrix the matrix to bind
  42693. */
  42694. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  42695. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  42696. };
  42697. PushMaterial.prototype.bind = function (world, mesh) {
  42698. if (!mesh) {
  42699. return;
  42700. }
  42701. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  42702. };
  42703. PushMaterial.prototype._afterBind = function (mesh, effect) {
  42704. if (effect === void 0) { effect = null; }
  42705. _super.prototype._afterBind.call(this, mesh);
  42706. this.getScene()._cachedEffect = effect;
  42707. };
  42708. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  42709. if (visibility === void 0) { visibility = 1; }
  42710. return scene.isCachedMaterialInvalid(this, effect, visibility);
  42711. };
  42712. return PushMaterial;
  42713. }(BABYLON.Material));
  42714. BABYLON.PushMaterial = PushMaterial;
  42715. })(BABYLON || (BABYLON = {}));
  42716. //# sourceMappingURL=babylon.pushMaterial.js.map
  42717. var BABYLON;
  42718. (function (BABYLON) {
  42719. /** @hidden */
  42720. var StandardMaterialDefines = /** @class */ (function (_super) {
  42721. __extends(StandardMaterialDefines, _super);
  42722. function StandardMaterialDefines() {
  42723. var _this = _super.call(this) || this;
  42724. _this.MAINUV1 = false;
  42725. _this.MAINUV2 = false;
  42726. _this.DIFFUSE = false;
  42727. _this.DIFFUSEDIRECTUV = 0;
  42728. _this.AMBIENT = false;
  42729. _this.AMBIENTDIRECTUV = 0;
  42730. _this.OPACITY = false;
  42731. _this.OPACITYDIRECTUV = 0;
  42732. _this.OPACITYRGB = false;
  42733. _this.REFLECTION = false;
  42734. _this.EMISSIVE = false;
  42735. _this.EMISSIVEDIRECTUV = 0;
  42736. _this.SPECULAR = false;
  42737. _this.SPECULARDIRECTUV = 0;
  42738. _this.BUMP = false;
  42739. _this.BUMPDIRECTUV = 0;
  42740. _this.PARALLAX = false;
  42741. _this.PARALLAXOCCLUSION = false;
  42742. _this.SPECULAROVERALPHA = false;
  42743. _this.CLIPPLANE = false;
  42744. _this.ALPHATEST = false;
  42745. _this.DEPTHPREPASS = false;
  42746. _this.ALPHAFROMDIFFUSE = false;
  42747. _this.POINTSIZE = false;
  42748. _this.FOG = false;
  42749. _this.SPECULARTERM = false;
  42750. _this.DIFFUSEFRESNEL = false;
  42751. _this.OPACITYFRESNEL = false;
  42752. _this.REFLECTIONFRESNEL = false;
  42753. _this.REFRACTIONFRESNEL = false;
  42754. _this.EMISSIVEFRESNEL = false;
  42755. _this.FRESNEL = false;
  42756. _this.NORMAL = false;
  42757. _this.UV1 = false;
  42758. _this.UV2 = false;
  42759. _this.VERTEXCOLOR = false;
  42760. _this.VERTEXALPHA = false;
  42761. _this.NUM_BONE_INFLUENCERS = 0;
  42762. _this.BonesPerMesh = 0;
  42763. _this.INSTANCES = false;
  42764. _this.GLOSSINESS = false;
  42765. _this.ROUGHNESS = false;
  42766. _this.EMISSIVEASILLUMINATION = false;
  42767. _this.LINKEMISSIVEWITHDIFFUSE = false;
  42768. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  42769. _this.LIGHTMAP = false;
  42770. _this.LIGHTMAPDIRECTUV = 0;
  42771. _this.OBJECTSPACE_NORMALMAP = false;
  42772. _this.USELIGHTMAPASSHADOWMAP = false;
  42773. _this.REFLECTIONMAP_3D = false;
  42774. _this.REFLECTIONMAP_SPHERICAL = false;
  42775. _this.REFLECTIONMAP_PLANAR = false;
  42776. _this.REFLECTIONMAP_CUBIC = false;
  42777. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  42778. _this.REFLECTIONMAP_PROJECTION = false;
  42779. _this.REFLECTIONMAP_SKYBOX = false;
  42780. _this.REFLECTIONMAP_EXPLICIT = false;
  42781. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  42782. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  42783. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  42784. _this.INVERTCUBICMAP = false;
  42785. _this.LOGARITHMICDEPTH = false;
  42786. _this.REFRACTION = false;
  42787. _this.REFRACTIONMAP_3D = false;
  42788. _this.REFLECTIONOVERALPHA = false;
  42789. _this.TWOSIDEDLIGHTING = false;
  42790. _this.SHADOWFLOAT = false;
  42791. _this.MORPHTARGETS = false;
  42792. _this.MORPHTARGETS_NORMAL = false;
  42793. _this.MORPHTARGETS_TANGENT = false;
  42794. _this.NUM_MORPH_INFLUENCERS = 0;
  42795. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  42796. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  42797. _this.IMAGEPROCESSING = false;
  42798. _this.VIGNETTE = false;
  42799. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  42800. _this.VIGNETTEBLENDMODEOPAQUE = false;
  42801. _this.TONEMAPPING = false;
  42802. _this.CONTRAST = false;
  42803. _this.COLORCURVES = false;
  42804. _this.COLORGRADING = false;
  42805. _this.COLORGRADING3D = false;
  42806. _this.SAMPLER3DGREENDEPTH = false;
  42807. _this.SAMPLER3DBGRMAP = false;
  42808. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  42809. /**
  42810. * If the reflection texture on this material is in linear color space
  42811. * @hidden
  42812. */
  42813. _this.IS_REFLECTION_LINEAR = false;
  42814. /**
  42815. * If the refraction texture on this material is in linear color space
  42816. * @hidden
  42817. */
  42818. _this.IS_REFRACTION_LINEAR = false;
  42819. _this.EXPOSURE = false;
  42820. _this.rebuild();
  42821. return _this;
  42822. }
  42823. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  42824. var modes = [
  42825. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  42826. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  42827. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  42828. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  42829. ];
  42830. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  42831. var mode = modes_1[_i];
  42832. this[mode] = (mode === modeToEnable);
  42833. }
  42834. };
  42835. return StandardMaterialDefines;
  42836. }(BABYLON.MaterialDefines));
  42837. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  42838. var StandardMaterial = /** @class */ (function (_super) {
  42839. __extends(StandardMaterial, _super);
  42840. function StandardMaterial(name, scene) {
  42841. var _this = _super.call(this, name, scene) || this;
  42842. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  42843. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  42844. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  42845. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42846. _this.specularPower = 64;
  42847. _this._useAlphaFromDiffuseTexture = false;
  42848. _this._useEmissiveAsIllumination = false;
  42849. _this._linkEmissiveWithDiffuse = false;
  42850. _this._useSpecularOverAlpha = false;
  42851. _this._useReflectionOverAlpha = false;
  42852. _this._disableLighting = false;
  42853. _this._useObjectSpaceNormalMap = false;
  42854. _this._useParallax = false;
  42855. _this._useParallaxOcclusion = false;
  42856. _this.parallaxScaleBias = 0.05;
  42857. _this._roughness = 0;
  42858. _this.indexOfRefraction = 0.98;
  42859. _this.invertRefractionY = true;
  42860. /**
  42861. * Defines the alpha limits in alpha test mode
  42862. */
  42863. _this.alphaCutOff = 0.4;
  42864. _this._useLightmapAsShadowmap = false;
  42865. _this._useReflectionFresnelFromSpecular = false;
  42866. _this._useGlossinessFromSpecularMapAlpha = false;
  42867. _this._maxSimultaneousLights = 4;
  42868. /**
  42869. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  42870. */
  42871. _this._invertNormalMapX = false;
  42872. /**
  42873. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42874. */
  42875. _this._invertNormalMapY = false;
  42876. /**
  42877. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42878. */
  42879. _this._twoSidedLighting = false;
  42880. _this._renderTargets = new BABYLON.SmartArray(16);
  42881. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  42882. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  42883. // Setup the default processing configuration to the scene.
  42884. _this._attachImageProcessingConfiguration(null);
  42885. _this.getRenderTargetTextures = function () {
  42886. _this._renderTargets.reset();
  42887. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  42888. _this._renderTargets.push(_this._reflectionTexture);
  42889. }
  42890. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  42891. _this._renderTargets.push(_this._refractionTexture);
  42892. }
  42893. return _this._renderTargets;
  42894. };
  42895. return _this;
  42896. }
  42897. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  42898. /**
  42899. * Gets the image processing configuration used either in this material.
  42900. */
  42901. get: function () {
  42902. return this._imageProcessingConfiguration;
  42903. },
  42904. /**
  42905. * Sets the Default image processing configuration used either in the this material.
  42906. *
  42907. * If sets to null, the scene one is in use.
  42908. */
  42909. set: function (value) {
  42910. this._attachImageProcessingConfiguration(value);
  42911. // Ensure the effect will be rebuilt.
  42912. this._markAllSubMeshesAsTexturesDirty();
  42913. },
  42914. enumerable: true,
  42915. configurable: true
  42916. });
  42917. /**
  42918. * Attaches a new image processing configuration to the Standard Material.
  42919. * @param configuration
  42920. */
  42921. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  42922. var _this = this;
  42923. if (configuration === this._imageProcessingConfiguration) {
  42924. return;
  42925. }
  42926. // Detaches observer.
  42927. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42928. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42929. }
  42930. // Pick the scene configuration if needed.
  42931. if (!configuration) {
  42932. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  42933. }
  42934. else {
  42935. this._imageProcessingConfiguration = configuration;
  42936. }
  42937. // Attaches observer.
  42938. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  42939. _this._markAllSubMeshesAsImageProcessingDirty();
  42940. });
  42941. };
  42942. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  42943. /**
  42944. * Gets wether the color curves effect is enabled.
  42945. */
  42946. get: function () {
  42947. return this.imageProcessingConfiguration.colorCurvesEnabled;
  42948. },
  42949. /**
  42950. * Sets wether the color curves effect is enabled.
  42951. */
  42952. set: function (value) {
  42953. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42954. },
  42955. enumerable: true,
  42956. configurable: true
  42957. });
  42958. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  42959. /**
  42960. * Gets wether the color grading effect is enabled.
  42961. */
  42962. get: function () {
  42963. return this.imageProcessingConfiguration.colorGradingEnabled;
  42964. },
  42965. /**
  42966. * Gets wether the color grading effect is enabled.
  42967. */
  42968. set: function (value) {
  42969. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42970. },
  42971. enumerable: true,
  42972. configurable: true
  42973. });
  42974. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  42975. /**
  42976. * Gets wether tonemapping is enabled or not.
  42977. */
  42978. get: function () {
  42979. return this._imageProcessingConfiguration.toneMappingEnabled;
  42980. },
  42981. /**
  42982. * Sets wether tonemapping is enabled or not
  42983. */
  42984. set: function (value) {
  42985. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42986. },
  42987. enumerable: true,
  42988. configurable: true
  42989. });
  42990. ;
  42991. ;
  42992. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  42993. /**
  42994. * The camera exposure used on this material.
  42995. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42996. * This corresponds to a photographic exposure.
  42997. */
  42998. get: function () {
  42999. return this._imageProcessingConfiguration.exposure;
  43000. },
  43001. /**
  43002. * The camera exposure used on this material.
  43003. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  43004. * This corresponds to a photographic exposure.
  43005. */
  43006. set: function (value) {
  43007. this._imageProcessingConfiguration.exposure = value;
  43008. },
  43009. enumerable: true,
  43010. configurable: true
  43011. });
  43012. ;
  43013. ;
  43014. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  43015. /**
  43016. * Gets The camera contrast used on this material.
  43017. */
  43018. get: function () {
  43019. return this._imageProcessingConfiguration.contrast;
  43020. },
  43021. /**
  43022. * Sets The camera contrast used on this material.
  43023. */
  43024. set: function (value) {
  43025. this._imageProcessingConfiguration.contrast = value;
  43026. },
  43027. enumerable: true,
  43028. configurable: true
  43029. });
  43030. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  43031. /**
  43032. * Gets the Color Grading 2D Lookup Texture.
  43033. */
  43034. get: function () {
  43035. return this._imageProcessingConfiguration.colorGradingTexture;
  43036. },
  43037. /**
  43038. * Sets the Color Grading 2D Lookup Texture.
  43039. */
  43040. set: function (value) {
  43041. this._imageProcessingConfiguration.colorGradingTexture = value;
  43042. },
  43043. enumerable: true,
  43044. configurable: true
  43045. });
  43046. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  43047. /**
  43048. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  43049. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  43050. * 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;
  43051. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  43052. */
  43053. get: function () {
  43054. return this._imageProcessingConfiguration.colorCurves;
  43055. },
  43056. /**
  43057. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  43058. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  43059. * 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;
  43060. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  43061. */
  43062. set: function (value) {
  43063. this._imageProcessingConfiguration.colorCurves = value;
  43064. },
  43065. enumerable: true,
  43066. configurable: true
  43067. });
  43068. StandardMaterial.prototype.getClassName = function () {
  43069. return "StandardMaterial";
  43070. };
  43071. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  43072. get: function () {
  43073. return this._useLogarithmicDepth;
  43074. },
  43075. set: function (value) {
  43076. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43077. this._markAllSubMeshesAsMiscDirty();
  43078. },
  43079. enumerable: true,
  43080. configurable: true
  43081. });
  43082. StandardMaterial.prototype.needAlphaBlending = function () {
  43083. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  43084. };
  43085. StandardMaterial.prototype.needAlphaTesting = function () {
  43086. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  43087. };
  43088. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  43089. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  43090. };
  43091. StandardMaterial.prototype.getAlphaTestTexture = function () {
  43092. return this._diffuseTexture;
  43093. };
  43094. /**
  43095. * Child classes can use it to update shaders
  43096. */
  43097. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43098. if (useInstances === void 0) { useInstances = false; }
  43099. if (subMesh.effect && this.isFrozen) {
  43100. if (this._wasPreviouslyReady && subMesh.effect) {
  43101. return true;
  43102. }
  43103. }
  43104. if (!subMesh._materialDefines) {
  43105. subMesh._materialDefines = new StandardMaterialDefines();
  43106. }
  43107. var scene = this.getScene();
  43108. var defines = subMesh._materialDefines;
  43109. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43110. if (defines._renderId === scene.getRenderId()) {
  43111. return true;
  43112. }
  43113. }
  43114. var engine = scene.getEngine();
  43115. // Lights
  43116. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  43117. // Textures
  43118. if (defines._areTexturesDirty) {
  43119. defines._needUVs = false;
  43120. defines.MAINUV1 = false;
  43121. defines.MAINUV2 = false;
  43122. if (scene.texturesEnabled) {
  43123. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43124. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  43125. return false;
  43126. }
  43127. else {
  43128. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  43129. }
  43130. }
  43131. else {
  43132. defines.DIFFUSE = false;
  43133. }
  43134. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43135. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43136. return false;
  43137. }
  43138. else {
  43139. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  43140. }
  43141. }
  43142. else {
  43143. defines.AMBIENT = false;
  43144. }
  43145. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43146. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43147. return false;
  43148. }
  43149. else {
  43150. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  43151. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  43152. }
  43153. }
  43154. else {
  43155. defines.OPACITY = false;
  43156. }
  43157. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43158. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  43159. return false;
  43160. }
  43161. else {
  43162. defines._needNormals = true;
  43163. defines.REFLECTION = true;
  43164. defines.ROUGHNESS = (this._roughness > 0);
  43165. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  43166. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  43167. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  43168. switch (this._reflectionTexture.coordinatesMode) {
  43169. case BABYLON.Texture.EXPLICIT_MODE:
  43170. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  43171. break;
  43172. case BABYLON.Texture.PLANAR_MODE:
  43173. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  43174. break;
  43175. case BABYLON.Texture.PROJECTION_MODE:
  43176. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  43177. break;
  43178. case BABYLON.Texture.SKYBOX_MODE:
  43179. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  43180. break;
  43181. case BABYLON.Texture.SPHERICAL_MODE:
  43182. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  43183. break;
  43184. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  43185. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  43186. break;
  43187. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  43188. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  43189. break;
  43190. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  43191. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  43192. break;
  43193. case BABYLON.Texture.CUBIC_MODE:
  43194. case BABYLON.Texture.INVCUBIC_MODE:
  43195. default:
  43196. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  43197. break;
  43198. }
  43199. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  43200. }
  43201. }
  43202. else {
  43203. defines.REFLECTION = false;
  43204. }
  43205. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43206. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43207. return false;
  43208. }
  43209. else {
  43210. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  43211. }
  43212. }
  43213. else {
  43214. defines.EMISSIVE = false;
  43215. }
  43216. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43217. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43218. return false;
  43219. }
  43220. else {
  43221. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  43222. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  43223. }
  43224. }
  43225. else {
  43226. defines.LIGHTMAP = false;
  43227. }
  43228. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43229. if (!this._specularTexture.isReadyOrNotBlocking()) {
  43230. return false;
  43231. }
  43232. else {
  43233. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  43234. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  43235. }
  43236. }
  43237. else {
  43238. defines.SPECULAR = false;
  43239. }
  43240. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  43241. // Bump texure can not be not blocking.
  43242. if (!this._bumpTexture.isReady()) {
  43243. return false;
  43244. }
  43245. else {
  43246. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  43247. defines.PARALLAX = this._useParallax;
  43248. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  43249. }
  43250. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  43251. }
  43252. else {
  43253. defines.BUMP = false;
  43254. }
  43255. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43256. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  43257. return false;
  43258. }
  43259. else {
  43260. defines._needUVs = true;
  43261. defines.REFRACTION = true;
  43262. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  43263. }
  43264. }
  43265. else {
  43266. defines.REFRACTION = false;
  43267. }
  43268. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  43269. }
  43270. else {
  43271. defines.DIFFUSE = false;
  43272. defines.AMBIENT = false;
  43273. defines.OPACITY = false;
  43274. defines.REFLECTION = false;
  43275. defines.EMISSIVE = false;
  43276. defines.LIGHTMAP = false;
  43277. defines.BUMP = false;
  43278. defines.REFRACTION = false;
  43279. }
  43280. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  43281. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  43282. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  43283. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  43284. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  43285. }
  43286. if (defines._areImageProcessingDirty) {
  43287. if (!this._imageProcessingConfiguration.isReady()) {
  43288. return false;
  43289. }
  43290. this._imageProcessingConfiguration.prepareDefines(defines);
  43291. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  43292. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  43293. }
  43294. if (defines._areFresnelDirty) {
  43295. if (StandardMaterial.FresnelEnabled) {
  43296. // Fresnel
  43297. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  43298. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  43299. this._reflectionFresnelParameters) {
  43300. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  43301. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  43302. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  43303. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  43304. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  43305. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  43306. defines._needNormals = true;
  43307. defines.FRESNEL = true;
  43308. }
  43309. }
  43310. else {
  43311. defines.FRESNEL = false;
  43312. }
  43313. }
  43314. // Misc.
  43315. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  43316. // Attribs
  43317. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  43318. // Values that need to be evaluated on every frame
  43319. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  43320. // Get correct effect
  43321. if (defines.isDirty) {
  43322. defines.markAsProcessed();
  43323. scene.resetCachedMaterial();
  43324. // Fallbacks
  43325. var fallbacks = new BABYLON.EffectFallbacks();
  43326. if (defines.REFLECTION) {
  43327. fallbacks.addFallback(0, "REFLECTION");
  43328. }
  43329. if (defines.SPECULAR) {
  43330. fallbacks.addFallback(0, "SPECULAR");
  43331. }
  43332. if (defines.BUMP) {
  43333. fallbacks.addFallback(0, "BUMP");
  43334. }
  43335. if (defines.PARALLAX) {
  43336. fallbacks.addFallback(1, "PARALLAX");
  43337. }
  43338. if (defines.PARALLAXOCCLUSION) {
  43339. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  43340. }
  43341. if (defines.SPECULAROVERALPHA) {
  43342. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  43343. }
  43344. if (defines.FOG) {
  43345. fallbacks.addFallback(1, "FOG");
  43346. }
  43347. if (defines.POINTSIZE) {
  43348. fallbacks.addFallback(0, "POINTSIZE");
  43349. }
  43350. if (defines.LOGARITHMICDEPTH) {
  43351. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  43352. }
  43353. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  43354. if (defines.SPECULARTERM) {
  43355. fallbacks.addFallback(0, "SPECULARTERM");
  43356. }
  43357. if (defines.DIFFUSEFRESNEL) {
  43358. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  43359. }
  43360. if (defines.OPACITYFRESNEL) {
  43361. fallbacks.addFallback(2, "OPACITYFRESNEL");
  43362. }
  43363. if (defines.REFLECTIONFRESNEL) {
  43364. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  43365. }
  43366. if (defines.EMISSIVEFRESNEL) {
  43367. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  43368. }
  43369. if (defines.FRESNEL) {
  43370. fallbacks.addFallback(4, "FRESNEL");
  43371. }
  43372. //Attributes
  43373. var attribs = [BABYLON.VertexBuffer.PositionKind];
  43374. if (defines.NORMAL) {
  43375. attribs.push(BABYLON.VertexBuffer.NormalKind);
  43376. }
  43377. if (defines.UV1) {
  43378. attribs.push(BABYLON.VertexBuffer.UVKind);
  43379. }
  43380. if (defines.UV2) {
  43381. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43382. }
  43383. if (defines.VERTEXCOLOR) {
  43384. attribs.push(BABYLON.VertexBuffer.ColorKind);
  43385. }
  43386. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  43387. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  43388. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  43389. var shaderName = "default";
  43390. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  43391. "vFogInfos", "vFogColor", "pointSize",
  43392. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  43393. "mBones",
  43394. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  43395. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  43396. "vReflectionPosition", "vReflectionSize",
  43397. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  43398. ];
  43399. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  43400. var uniformBuffers = ["Material", "Scene"];
  43401. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  43402. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  43403. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  43404. uniformsNames: uniforms,
  43405. uniformBuffersNames: uniformBuffers,
  43406. samplers: samplers,
  43407. defines: defines,
  43408. maxSimultaneousLights: this._maxSimultaneousLights
  43409. });
  43410. if (this.customShaderNameResolve) {
  43411. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  43412. }
  43413. var join = defines.toString();
  43414. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  43415. attributes: attribs,
  43416. uniformsNames: uniforms,
  43417. uniformBuffersNames: uniformBuffers,
  43418. samplers: samplers,
  43419. defines: join,
  43420. fallbacks: fallbacks,
  43421. onCompiled: this.onCompiled,
  43422. onError: this.onError,
  43423. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  43424. }, engine), defines);
  43425. this.buildUniformLayout();
  43426. }
  43427. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43428. return false;
  43429. }
  43430. defines._renderId = scene.getRenderId();
  43431. this._wasPreviouslyReady = true;
  43432. return true;
  43433. };
  43434. StandardMaterial.prototype.buildUniformLayout = function () {
  43435. // Order is important !
  43436. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  43437. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  43438. this._uniformBuffer.addUniform("opacityParts", 4);
  43439. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  43440. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  43441. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  43442. this._uniformBuffer.addUniform("refractionRightColor", 4);
  43443. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  43444. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  43445. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  43446. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  43447. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  43448. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  43449. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  43450. this._uniformBuffer.addUniform("vReflectionSize", 3);
  43451. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  43452. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  43453. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  43454. this._uniformBuffer.addUniform("vBumpInfos", 3);
  43455. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  43456. this._uniformBuffer.addUniform("ambientMatrix", 16);
  43457. this._uniformBuffer.addUniform("opacityMatrix", 16);
  43458. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  43459. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  43460. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  43461. this._uniformBuffer.addUniform("specularMatrix", 16);
  43462. this._uniformBuffer.addUniform("bumpMatrix", 16);
  43463. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  43464. this._uniformBuffer.addUniform("refractionMatrix", 16);
  43465. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  43466. this._uniformBuffer.addUniform("vSpecularColor", 4);
  43467. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  43468. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  43469. this._uniformBuffer.addUniform("pointSize", 1);
  43470. this._uniformBuffer.create();
  43471. };
  43472. StandardMaterial.prototype.unbind = function () {
  43473. if (this._activeEffect) {
  43474. var needFlag = false;
  43475. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  43476. this._activeEffect.setTexture("reflection2DSampler", null);
  43477. needFlag = true;
  43478. }
  43479. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  43480. this._activeEffect.setTexture("refraction2DSampler", null);
  43481. needFlag = true;
  43482. }
  43483. if (needFlag) {
  43484. this._markAllSubMeshesAsTexturesDirty();
  43485. }
  43486. }
  43487. _super.prototype.unbind.call(this);
  43488. };
  43489. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  43490. var scene = this.getScene();
  43491. var defines = subMesh._materialDefines;
  43492. if (!defines) {
  43493. return;
  43494. }
  43495. var effect = subMesh.effect;
  43496. if (!effect) {
  43497. return;
  43498. }
  43499. this._activeEffect = effect;
  43500. // Matrices
  43501. this.bindOnlyWorldMatrix(world);
  43502. // Normal Matrix
  43503. if (defines.OBJECTSPACE_NORMALMAP) {
  43504. world.toNormalMatrix(this._normalMatrix);
  43505. this.bindOnlyNormalMatrix(this._normalMatrix);
  43506. }
  43507. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  43508. // Bones
  43509. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  43510. if (mustRebind) {
  43511. this._uniformBuffer.bindToEffect(effect, "Material");
  43512. this.bindViewProjection(effect);
  43513. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  43514. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  43515. // Fresnel
  43516. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  43517. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  43518. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  43519. }
  43520. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  43521. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  43522. }
  43523. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  43524. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  43525. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  43526. }
  43527. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  43528. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  43529. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  43530. }
  43531. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  43532. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  43533. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  43534. }
  43535. }
  43536. // Textures
  43537. if (scene.texturesEnabled) {
  43538. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43539. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  43540. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  43541. if (this._diffuseTexture.hasAlpha) {
  43542. effect.setFloat("alphaCutOff", this.alphaCutOff);
  43543. }
  43544. }
  43545. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43546. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  43547. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  43548. }
  43549. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43550. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  43551. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  43552. }
  43553. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43554. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  43555. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  43556. if (this._reflectionTexture.boundingBoxSize) {
  43557. var cubeTexture = this._reflectionTexture;
  43558. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  43559. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  43560. }
  43561. }
  43562. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43563. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  43564. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  43565. }
  43566. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43567. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  43568. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  43569. }
  43570. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43571. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  43572. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  43573. }
  43574. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43575. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  43576. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  43577. if (scene._mirroredCameraPosition) {
  43578. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  43579. }
  43580. else {
  43581. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  43582. }
  43583. }
  43584. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43585. var depth = 1.0;
  43586. if (!this._refractionTexture.isCube) {
  43587. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  43588. if (this._refractionTexture.depth) {
  43589. depth = this._refractionTexture.depth;
  43590. }
  43591. }
  43592. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  43593. }
  43594. }
  43595. // Point size
  43596. if (this.pointsCloud) {
  43597. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  43598. }
  43599. if (defines.SPECULARTERM) {
  43600. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  43601. }
  43602. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  43603. // Diffuse
  43604. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  43605. }
  43606. // Textures
  43607. if (scene.texturesEnabled) {
  43608. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43609. effect.setTexture("diffuseSampler", this._diffuseTexture);
  43610. }
  43611. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43612. effect.setTexture("ambientSampler", this._ambientTexture);
  43613. }
  43614. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43615. effect.setTexture("opacitySampler", this._opacityTexture);
  43616. }
  43617. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43618. if (this._reflectionTexture.isCube) {
  43619. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  43620. }
  43621. else {
  43622. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  43623. }
  43624. }
  43625. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43626. effect.setTexture("emissiveSampler", this._emissiveTexture);
  43627. }
  43628. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43629. effect.setTexture("lightmapSampler", this._lightmapTexture);
  43630. }
  43631. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43632. effect.setTexture("specularSampler", this._specularTexture);
  43633. }
  43634. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43635. effect.setTexture("bumpSampler", this._bumpTexture);
  43636. }
  43637. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43638. var depth = 1.0;
  43639. if (this._refractionTexture.isCube) {
  43640. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  43641. }
  43642. else {
  43643. effect.setTexture("refraction2DSampler", this._refractionTexture);
  43644. }
  43645. }
  43646. }
  43647. // Clip plane
  43648. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  43649. // Colors
  43650. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  43651. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  43652. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  43653. }
  43654. if (mustRebind || !this.isFrozen) {
  43655. // Lights
  43656. if (scene.lightsEnabled && !this._disableLighting) {
  43657. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  43658. }
  43659. // View
  43660. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  43661. this.bindView(effect);
  43662. }
  43663. // Fog
  43664. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  43665. // Morph targets
  43666. if (defines.NUM_MORPH_INFLUENCERS) {
  43667. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  43668. }
  43669. // Log. depth
  43670. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  43671. // image processing
  43672. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  43673. this._imageProcessingConfiguration.bind(this._activeEffect);
  43674. }
  43675. }
  43676. this._uniformBuffer.update();
  43677. this._afterBind(mesh, this._activeEffect);
  43678. };
  43679. StandardMaterial.prototype.getAnimatables = function () {
  43680. var results = [];
  43681. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  43682. results.push(this._diffuseTexture);
  43683. }
  43684. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  43685. results.push(this._ambientTexture);
  43686. }
  43687. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  43688. results.push(this._opacityTexture);
  43689. }
  43690. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  43691. results.push(this._reflectionTexture);
  43692. }
  43693. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  43694. results.push(this._emissiveTexture);
  43695. }
  43696. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  43697. results.push(this._specularTexture);
  43698. }
  43699. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  43700. results.push(this._bumpTexture);
  43701. }
  43702. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  43703. results.push(this._lightmapTexture);
  43704. }
  43705. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  43706. results.push(this._refractionTexture);
  43707. }
  43708. return results;
  43709. };
  43710. StandardMaterial.prototype.getActiveTextures = function () {
  43711. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43712. if (this._diffuseTexture) {
  43713. activeTextures.push(this._diffuseTexture);
  43714. }
  43715. if (this._ambientTexture) {
  43716. activeTextures.push(this._ambientTexture);
  43717. }
  43718. if (this._opacityTexture) {
  43719. activeTextures.push(this._opacityTexture);
  43720. }
  43721. if (this._reflectionTexture) {
  43722. activeTextures.push(this._reflectionTexture);
  43723. }
  43724. if (this._emissiveTexture) {
  43725. activeTextures.push(this._emissiveTexture);
  43726. }
  43727. if (this._specularTexture) {
  43728. activeTextures.push(this._specularTexture);
  43729. }
  43730. if (this._bumpTexture) {
  43731. activeTextures.push(this._bumpTexture);
  43732. }
  43733. if (this._lightmapTexture) {
  43734. activeTextures.push(this._lightmapTexture);
  43735. }
  43736. if (this._refractionTexture) {
  43737. activeTextures.push(this._refractionTexture);
  43738. }
  43739. return activeTextures;
  43740. };
  43741. StandardMaterial.prototype.hasTexture = function (texture) {
  43742. if (_super.prototype.hasTexture.call(this, texture)) {
  43743. return true;
  43744. }
  43745. if (this._diffuseTexture === texture) {
  43746. return true;
  43747. }
  43748. if (this._ambientTexture === texture) {
  43749. return true;
  43750. }
  43751. if (this._opacityTexture === texture) {
  43752. return true;
  43753. }
  43754. if (this._reflectionTexture === texture) {
  43755. return true;
  43756. }
  43757. if (this._emissiveTexture === texture) {
  43758. return true;
  43759. }
  43760. if (this._specularTexture === texture) {
  43761. return true;
  43762. }
  43763. if (this._bumpTexture === texture) {
  43764. return true;
  43765. }
  43766. if (this._lightmapTexture === texture) {
  43767. return true;
  43768. }
  43769. if (this._refractionTexture === texture) {
  43770. return true;
  43771. }
  43772. return false;
  43773. };
  43774. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  43775. if (forceDisposeTextures) {
  43776. if (this._diffuseTexture) {
  43777. this._diffuseTexture.dispose();
  43778. }
  43779. if (this._ambientTexture) {
  43780. this._ambientTexture.dispose();
  43781. }
  43782. if (this._opacityTexture) {
  43783. this._opacityTexture.dispose();
  43784. }
  43785. if (this._reflectionTexture) {
  43786. this._reflectionTexture.dispose();
  43787. }
  43788. if (this._emissiveTexture) {
  43789. this._emissiveTexture.dispose();
  43790. }
  43791. if (this._specularTexture) {
  43792. this._specularTexture.dispose();
  43793. }
  43794. if (this._bumpTexture) {
  43795. this._bumpTexture.dispose();
  43796. }
  43797. if (this._lightmapTexture) {
  43798. this._lightmapTexture.dispose();
  43799. }
  43800. if (this._refractionTexture) {
  43801. this._refractionTexture.dispose();
  43802. }
  43803. }
  43804. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43805. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43806. }
  43807. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  43808. };
  43809. StandardMaterial.prototype.clone = function (name) {
  43810. var _this = this;
  43811. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  43812. result.name = name;
  43813. result.id = name;
  43814. return result;
  43815. };
  43816. StandardMaterial.prototype.serialize = function () {
  43817. return BABYLON.SerializationHelper.Serialize(this);
  43818. };
  43819. // Statics
  43820. StandardMaterial.Parse = function (source, scene, rootUrl) {
  43821. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  43822. };
  43823. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  43824. get: function () {
  43825. return StandardMaterial._DiffuseTextureEnabled;
  43826. },
  43827. set: function (value) {
  43828. if (StandardMaterial._DiffuseTextureEnabled === value) {
  43829. return;
  43830. }
  43831. StandardMaterial._DiffuseTextureEnabled = value;
  43832. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43833. },
  43834. enumerable: true,
  43835. configurable: true
  43836. });
  43837. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  43838. get: function () {
  43839. return StandardMaterial._AmbientTextureEnabled;
  43840. },
  43841. set: function (value) {
  43842. if (StandardMaterial._AmbientTextureEnabled === value) {
  43843. return;
  43844. }
  43845. StandardMaterial._AmbientTextureEnabled = value;
  43846. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43847. },
  43848. enumerable: true,
  43849. configurable: true
  43850. });
  43851. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  43852. get: function () {
  43853. return StandardMaterial._OpacityTextureEnabled;
  43854. },
  43855. set: function (value) {
  43856. if (StandardMaterial._OpacityTextureEnabled === value) {
  43857. return;
  43858. }
  43859. StandardMaterial._OpacityTextureEnabled = value;
  43860. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43861. },
  43862. enumerable: true,
  43863. configurable: true
  43864. });
  43865. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  43866. get: function () {
  43867. return StandardMaterial._ReflectionTextureEnabled;
  43868. },
  43869. set: function (value) {
  43870. if (StandardMaterial._ReflectionTextureEnabled === value) {
  43871. return;
  43872. }
  43873. StandardMaterial._ReflectionTextureEnabled = value;
  43874. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43875. },
  43876. enumerable: true,
  43877. configurable: true
  43878. });
  43879. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  43880. get: function () {
  43881. return StandardMaterial._EmissiveTextureEnabled;
  43882. },
  43883. set: function (value) {
  43884. if (StandardMaterial._EmissiveTextureEnabled === value) {
  43885. return;
  43886. }
  43887. StandardMaterial._EmissiveTextureEnabled = value;
  43888. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43889. },
  43890. enumerable: true,
  43891. configurable: true
  43892. });
  43893. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  43894. get: function () {
  43895. return StandardMaterial._SpecularTextureEnabled;
  43896. },
  43897. set: function (value) {
  43898. if (StandardMaterial._SpecularTextureEnabled === value) {
  43899. return;
  43900. }
  43901. StandardMaterial._SpecularTextureEnabled = value;
  43902. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43903. },
  43904. enumerable: true,
  43905. configurable: true
  43906. });
  43907. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  43908. get: function () {
  43909. return StandardMaterial._BumpTextureEnabled;
  43910. },
  43911. set: function (value) {
  43912. if (StandardMaterial._BumpTextureEnabled === value) {
  43913. return;
  43914. }
  43915. StandardMaterial._BumpTextureEnabled = value;
  43916. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43917. },
  43918. enumerable: true,
  43919. configurable: true
  43920. });
  43921. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  43922. get: function () {
  43923. return StandardMaterial._LightmapTextureEnabled;
  43924. },
  43925. set: function (value) {
  43926. if (StandardMaterial._LightmapTextureEnabled === value) {
  43927. return;
  43928. }
  43929. StandardMaterial._LightmapTextureEnabled = value;
  43930. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43931. },
  43932. enumerable: true,
  43933. configurable: true
  43934. });
  43935. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  43936. get: function () {
  43937. return StandardMaterial._RefractionTextureEnabled;
  43938. },
  43939. set: function (value) {
  43940. if (StandardMaterial._RefractionTextureEnabled === value) {
  43941. return;
  43942. }
  43943. StandardMaterial._RefractionTextureEnabled = value;
  43944. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43945. },
  43946. enumerable: true,
  43947. configurable: true
  43948. });
  43949. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  43950. get: function () {
  43951. return StandardMaterial._ColorGradingTextureEnabled;
  43952. },
  43953. set: function (value) {
  43954. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  43955. return;
  43956. }
  43957. StandardMaterial._ColorGradingTextureEnabled = value;
  43958. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43959. },
  43960. enumerable: true,
  43961. configurable: true
  43962. });
  43963. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  43964. get: function () {
  43965. return StandardMaterial._FresnelEnabled;
  43966. },
  43967. set: function (value) {
  43968. if (StandardMaterial._FresnelEnabled === value) {
  43969. return;
  43970. }
  43971. StandardMaterial._FresnelEnabled = value;
  43972. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  43973. },
  43974. enumerable: true,
  43975. configurable: true
  43976. });
  43977. // Flags used to enable or disable a type of texture for all Standard Materials
  43978. StandardMaterial._DiffuseTextureEnabled = true;
  43979. StandardMaterial._AmbientTextureEnabled = true;
  43980. StandardMaterial._OpacityTextureEnabled = true;
  43981. StandardMaterial._ReflectionTextureEnabled = true;
  43982. StandardMaterial._EmissiveTextureEnabled = true;
  43983. StandardMaterial._SpecularTextureEnabled = true;
  43984. StandardMaterial._BumpTextureEnabled = true;
  43985. StandardMaterial._LightmapTextureEnabled = true;
  43986. StandardMaterial._RefractionTextureEnabled = true;
  43987. StandardMaterial._ColorGradingTextureEnabled = true;
  43988. StandardMaterial._FresnelEnabled = true;
  43989. __decorate([
  43990. BABYLON.serializeAsTexture("diffuseTexture")
  43991. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  43992. __decorate([
  43993. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43994. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  43995. __decorate([
  43996. BABYLON.serializeAsTexture("ambientTexture")
  43997. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  43998. __decorate([
  43999. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44000. ], StandardMaterial.prototype, "ambientTexture", void 0);
  44001. __decorate([
  44002. BABYLON.serializeAsTexture("opacityTexture")
  44003. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  44004. __decorate([
  44005. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  44006. ], StandardMaterial.prototype, "opacityTexture", void 0);
  44007. __decorate([
  44008. BABYLON.serializeAsTexture("reflectionTexture")
  44009. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  44010. __decorate([
  44011. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44012. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  44013. __decorate([
  44014. BABYLON.serializeAsTexture("emissiveTexture")
  44015. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  44016. __decorate([
  44017. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44018. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  44019. __decorate([
  44020. BABYLON.serializeAsTexture("specularTexture")
  44021. ], StandardMaterial.prototype, "_specularTexture", void 0);
  44022. __decorate([
  44023. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44024. ], StandardMaterial.prototype, "specularTexture", void 0);
  44025. __decorate([
  44026. BABYLON.serializeAsTexture("bumpTexture")
  44027. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  44028. __decorate([
  44029. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44030. ], StandardMaterial.prototype, "bumpTexture", void 0);
  44031. __decorate([
  44032. BABYLON.serializeAsTexture("lightmapTexture")
  44033. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  44034. __decorate([
  44035. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44036. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  44037. __decorate([
  44038. BABYLON.serializeAsTexture("refractionTexture")
  44039. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  44040. __decorate([
  44041. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44042. ], StandardMaterial.prototype, "refractionTexture", void 0);
  44043. __decorate([
  44044. BABYLON.serializeAsColor3("ambient")
  44045. ], StandardMaterial.prototype, "ambientColor", void 0);
  44046. __decorate([
  44047. BABYLON.serializeAsColor3("diffuse")
  44048. ], StandardMaterial.prototype, "diffuseColor", void 0);
  44049. __decorate([
  44050. BABYLON.serializeAsColor3("specular")
  44051. ], StandardMaterial.prototype, "specularColor", void 0);
  44052. __decorate([
  44053. BABYLON.serializeAsColor3("emissive")
  44054. ], StandardMaterial.prototype, "emissiveColor", void 0);
  44055. __decorate([
  44056. BABYLON.serialize()
  44057. ], StandardMaterial.prototype, "specularPower", void 0);
  44058. __decorate([
  44059. BABYLON.serialize("useAlphaFromDiffuseTexture")
  44060. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  44061. __decorate([
  44062. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44063. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  44064. __decorate([
  44065. BABYLON.serialize("useEmissiveAsIllumination")
  44066. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  44067. __decorate([
  44068. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44069. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  44070. __decorate([
  44071. BABYLON.serialize("linkEmissiveWithDiffuse")
  44072. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  44073. __decorate([
  44074. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44075. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  44076. __decorate([
  44077. BABYLON.serialize("useSpecularOverAlpha")
  44078. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  44079. __decorate([
  44080. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44081. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  44082. __decorate([
  44083. BABYLON.serialize("useReflectionOverAlpha")
  44084. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  44085. __decorate([
  44086. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44087. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  44088. __decorate([
  44089. BABYLON.serialize("disableLighting")
  44090. ], StandardMaterial.prototype, "_disableLighting", void 0);
  44091. __decorate([
  44092. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44093. ], StandardMaterial.prototype, "disableLighting", void 0);
  44094. __decorate([
  44095. BABYLON.serialize("useObjectSpaceNormalMap")
  44096. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  44097. __decorate([
  44098. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44099. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  44100. __decorate([
  44101. BABYLON.serialize("useParallax")
  44102. ], StandardMaterial.prototype, "_useParallax", void 0);
  44103. __decorate([
  44104. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44105. ], StandardMaterial.prototype, "useParallax", void 0);
  44106. __decorate([
  44107. BABYLON.serialize("useParallaxOcclusion")
  44108. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  44109. __decorate([
  44110. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44111. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  44112. __decorate([
  44113. BABYLON.serialize()
  44114. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  44115. __decorate([
  44116. BABYLON.serialize("roughness")
  44117. ], StandardMaterial.prototype, "_roughness", void 0);
  44118. __decorate([
  44119. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44120. ], StandardMaterial.prototype, "roughness", void 0);
  44121. __decorate([
  44122. BABYLON.serialize()
  44123. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  44124. __decorate([
  44125. BABYLON.serialize()
  44126. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  44127. __decorate([
  44128. BABYLON.serialize()
  44129. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  44130. __decorate([
  44131. BABYLON.serialize("useLightmapAsShadowmap")
  44132. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  44133. __decorate([
  44134. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44135. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44136. __decorate([
  44137. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  44138. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  44139. __decorate([
  44140. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44141. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  44142. __decorate([
  44143. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  44144. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  44145. __decorate([
  44146. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  44147. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  44148. __decorate([
  44149. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  44150. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  44151. __decorate([
  44152. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44153. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  44154. __decorate([
  44155. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  44156. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  44157. __decorate([
  44158. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44159. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  44160. __decorate([
  44161. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  44162. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  44163. __decorate([
  44164. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44165. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  44166. __decorate([
  44167. BABYLON.serialize("useReflectionFresnelFromSpecular")
  44168. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  44169. __decorate([
  44170. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44171. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  44172. __decorate([
  44173. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  44174. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  44175. __decorate([
  44176. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44177. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  44178. __decorate([
  44179. BABYLON.serialize("maxSimultaneousLights")
  44180. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  44181. __decorate([
  44182. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44183. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  44184. __decorate([
  44185. BABYLON.serialize("invertNormalMapX")
  44186. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  44187. __decorate([
  44188. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44189. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  44190. __decorate([
  44191. BABYLON.serialize("invertNormalMapY")
  44192. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  44193. __decorate([
  44194. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44195. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  44196. __decorate([
  44197. BABYLON.serialize("twoSidedLighting")
  44198. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  44199. __decorate([
  44200. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44201. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  44202. __decorate([
  44203. BABYLON.serialize()
  44204. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  44205. return StandardMaterial;
  44206. }(BABYLON.PushMaterial));
  44207. BABYLON.StandardMaterial = StandardMaterial;
  44208. })(BABYLON || (BABYLON = {}));
  44209. //# sourceMappingURL=babylon.standardMaterial.js.map
  44210. var BABYLON;
  44211. (function (BABYLON) {
  44212. /**
  44213. * Manages the defines for the PBR Material.
  44214. * @hiddenChildren
  44215. */
  44216. var PBRMaterialDefines = /** @class */ (function (_super) {
  44217. __extends(PBRMaterialDefines, _super);
  44218. /**
  44219. * Initializes the PBR Material defines.
  44220. */
  44221. function PBRMaterialDefines() {
  44222. var _this = _super.call(this) || this;
  44223. _this.PBR = true;
  44224. _this.MAINUV1 = false;
  44225. _this.MAINUV2 = false;
  44226. _this.UV1 = false;
  44227. _this.UV2 = false;
  44228. _this.ALBEDO = false;
  44229. _this.ALBEDODIRECTUV = 0;
  44230. _this.VERTEXCOLOR = false;
  44231. _this.AMBIENT = false;
  44232. _this.AMBIENTDIRECTUV = 0;
  44233. _this.AMBIENTINGRAYSCALE = false;
  44234. _this.OPACITY = false;
  44235. _this.VERTEXALPHA = false;
  44236. _this.OPACITYDIRECTUV = 0;
  44237. _this.OPACITYRGB = false;
  44238. _this.ALPHATEST = false;
  44239. _this.DEPTHPREPASS = false;
  44240. _this.ALPHABLEND = false;
  44241. _this.ALPHAFROMALBEDO = false;
  44242. _this.ALPHATESTVALUE = "0.5";
  44243. _this.SPECULAROVERALPHA = false;
  44244. _this.RADIANCEOVERALPHA = false;
  44245. _this.ALPHAFRESNEL = false;
  44246. _this.LINEARALPHAFRESNEL = false;
  44247. _this.PREMULTIPLYALPHA = false;
  44248. _this.EMISSIVE = false;
  44249. _this.EMISSIVEDIRECTUV = 0;
  44250. _this.REFLECTIVITY = false;
  44251. _this.REFLECTIVITYDIRECTUV = 0;
  44252. _this.SPECULARTERM = false;
  44253. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  44254. _this.MICROSURFACEAUTOMATIC = false;
  44255. _this.LODBASEDMICROSFURACE = false;
  44256. _this.MICROSURFACEMAP = false;
  44257. _this.MICROSURFACEMAPDIRECTUV = 0;
  44258. _this.METALLICWORKFLOW = false;
  44259. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  44260. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  44261. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  44262. _this.AOSTOREINMETALMAPRED = false;
  44263. _this.ENVIRONMENTBRDF = false;
  44264. _this.NORMAL = false;
  44265. _this.TANGENT = false;
  44266. _this.BUMP = false;
  44267. _this.BUMPDIRECTUV = 0;
  44268. _this.OBJECTSPACE_NORMALMAP = false;
  44269. _this.PARALLAX = false;
  44270. _this.PARALLAXOCCLUSION = false;
  44271. _this.NORMALXYSCALE = true;
  44272. _this.LIGHTMAP = false;
  44273. _this.LIGHTMAPDIRECTUV = 0;
  44274. _this.USELIGHTMAPASSHADOWMAP = false;
  44275. _this.GAMMALIGHTMAP = false;
  44276. _this.REFLECTION = false;
  44277. _this.REFLECTIONMAP_3D = false;
  44278. _this.REFLECTIONMAP_SPHERICAL = false;
  44279. _this.REFLECTIONMAP_PLANAR = false;
  44280. _this.REFLECTIONMAP_CUBIC = false;
  44281. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44282. _this.REFLECTIONMAP_PROJECTION = false;
  44283. _this.REFLECTIONMAP_SKYBOX = false;
  44284. _this.REFLECTIONMAP_EXPLICIT = false;
  44285. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44286. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44287. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44288. _this.INVERTCUBICMAP = false;
  44289. _this.USESPHERICALFROMREFLECTIONMAP = false;
  44290. _this.USESPHERICALINVERTEX = false;
  44291. _this.REFLECTIONMAP_OPPOSITEZ = false;
  44292. _this.LODINREFLECTIONALPHA = false;
  44293. _this.GAMMAREFLECTION = false;
  44294. _this.RADIANCEOCCLUSION = false;
  44295. _this.HORIZONOCCLUSION = false;
  44296. _this.REFRACTION = false;
  44297. _this.REFRACTIONMAP_3D = false;
  44298. _this.REFRACTIONMAP_OPPOSITEZ = false;
  44299. _this.LODINREFRACTIONALPHA = false;
  44300. _this.GAMMAREFRACTION = false;
  44301. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  44302. _this.INSTANCES = false;
  44303. _this.NUM_BONE_INFLUENCERS = 0;
  44304. _this.BonesPerMesh = 0;
  44305. _this.NONUNIFORMSCALING = false;
  44306. _this.MORPHTARGETS = false;
  44307. _this.MORPHTARGETS_NORMAL = false;
  44308. _this.MORPHTARGETS_TANGENT = false;
  44309. _this.NUM_MORPH_INFLUENCERS = 0;
  44310. _this.IMAGEPROCESSING = false;
  44311. _this.VIGNETTE = false;
  44312. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  44313. _this.VIGNETTEBLENDMODEOPAQUE = false;
  44314. _this.TONEMAPPING = false;
  44315. _this.CONTRAST = false;
  44316. _this.COLORCURVES = false;
  44317. _this.COLORGRADING = false;
  44318. _this.COLORGRADING3D = false;
  44319. _this.SAMPLER3DGREENDEPTH = false;
  44320. _this.SAMPLER3DBGRMAP = false;
  44321. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  44322. _this.EXPOSURE = false;
  44323. _this.USEPHYSICALLIGHTFALLOFF = false;
  44324. _this.TWOSIDEDLIGHTING = false;
  44325. _this.SHADOWFLOAT = false;
  44326. _this.CLIPPLANE = false;
  44327. _this.POINTSIZE = false;
  44328. _this.FOG = false;
  44329. _this.LOGARITHMICDEPTH = false;
  44330. _this.FORCENORMALFORWARD = false;
  44331. _this.SPECULARAA = false;
  44332. _this.UNLIT = false;
  44333. _this.rebuild();
  44334. return _this;
  44335. }
  44336. /**
  44337. * Resets the PBR Material defines.
  44338. */
  44339. PBRMaterialDefines.prototype.reset = function () {
  44340. _super.prototype.reset.call(this);
  44341. this.ALPHATESTVALUE = "0.5";
  44342. this.PBR = true;
  44343. };
  44344. return PBRMaterialDefines;
  44345. }(BABYLON.MaterialDefines));
  44346. /**
  44347. * The Physically based material base class of BJS.
  44348. *
  44349. * This offers the main features of a standard PBR material.
  44350. * For more information, please refer to the documentation :
  44351. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44352. */
  44353. var PBRBaseMaterial = /** @class */ (function (_super) {
  44354. __extends(PBRBaseMaterial, _super);
  44355. /**
  44356. * Instantiates a new PBRMaterial instance.
  44357. *
  44358. * @param name The material name
  44359. * @param scene The scene the material will be use in.
  44360. */
  44361. function PBRBaseMaterial(name, scene) {
  44362. var _this = _super.call(this, name, scene) || this;
  44363. /**
  44364. * Intensity of the direct lights e.g. the four lights available in your scene.
  44365. * This impacts both the direct diffuse and specular highlights.
  44366. */
  44367. _this._directIntensity = 1.0;
  44368. /**
  44369. * Intensity of the emissive part of the material.
  44370. * This helps controlling the emissive effect without modifying the emissive color.
  44371. */
  44372. _this._emissiveIntensity = 1.0;
  44373. /**
  44374. * Intensity of the environment e.g. how much the environment will light the object
  44375. * either through harmonics for rough material or through the refelction for shiny ones.
  44376. */
  44377. _this._environmentIntensity = 1.0;
  44378. /**
  44379. * This is a special control allowing the reduction of the specular highlights coming from the
  44380. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44381. */
  44382. _this._specularIntensity = 1.0;
  44383. /**
  44384. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  44385. */
  44386. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  44387. /**
  44388. * Debug Control allowing disabling the bump map on this material.
  44389. */
  44390. _this._disableBumpMap = false;
  44391. /**
  44392. * AKA Occlusion Texture Intensity in other nomenclature.
  44393. */
  44394. _this._ambientTextureStrength = 1.0;
  44395. /**
  44396. * The color of a material in ambient lighting.
  44397. */
  44398. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  44399. /**
  44400. * AKA Diffuse Color in other nomenclature.
  44401. */
  44402. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  44403. /**
  44404. * AKA Specular Color in other nomenclature.
  44405. */
  44406. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44407. /**
  44408. * The color applied when light is reflected from a material.
  44409. */
  44410. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  44411. /**
  44412. * The color applied when light is emitted from a material.
  44413. */
  44414. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  44415. /**
  44416. * AKA Glossiness in other nomenclature.
  44417. */
  44418. _this._microSurface = 0.9;
  44419. /**
  44420. * source material index of refraction (IOR)' / 'destination material IOR.
  44421. */
  44422. _this._indexOfRefraction = 0.66;
  44423. /**
  44424. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  44425. */
  44426. _this._invertRefractionY = false;
  44427. /**
  44428. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44429. * Materials half opaque for instance using refraction could benefit from this control.
  44430. */
  44431. _this._linkRefractionWithTransparency = false;
  44432. /**
  44433. * Specifies that the material will use the light map as a show map.
  44434. */
  44435. _this._useLightmapAsShadowmap = false;
  44436. /**
  44437. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  44438. * makes the reflect vector face the model (under horizon).
  44439. */
  44440. _this._useHorizonOcclusion = true;
  44441. /**
  44442. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  44443. * too much the area relying on ambient texture to define their ambient occlusion.
  44444. */
  44445. _this._useRadianceOcclusion = true;
  44446. /**
  44447. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  44448. */
  44449. _this._useAlphaFromAlbedoTexture = false;
  44450. /**
  44451. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  44452. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  44453. */
  44454. _this._useSpecularOverAlpha = true;
  44455. /**
  44456. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  44457. */
  44458. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  44459. /**
  44460. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  44461. */
  44462. _this._useRoughnessFromMetallicTextureAlpha = true;
  44463. /**
  44464. * Specifies if the metallic texture contains the roughness information in its green channel.
  44465. */
  44466. _this._useRoughnessFromMetallicTextureGreen = false;
  44467. /**
  44468. * Specifies if the metallic texture contains the metallness information in its blue channel.
  44469. */
  44470. _this._useMetallnessFromMetallicTextureBlue = false;
  44471. /**
  44472. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  44473. */
  44474. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  44475. /**
  44476. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  44477. */
  44478. _this._useAmbientInGrayScale = false;
  44479. /**
  44480. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  44481. * The material will try to infer what glossiness each pixel should be.
  44482. */
  44483. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  44484. /**
  44485. * BJS is using an harcoded light falloff based on a manually sets up range.
  44486. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  44487. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  44488. */
  44489. _this._usePhysicalLightFalloff = true;
  44490. /**
  44491. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  44492. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  44493. */
  44494. _this._useRadianceOverAlpha = true;
  44495. /**
  44496. * Allows using an object space normal map (instead of tangent space).
  44497. */
  44498. _this._useObjectSpaceNormalMap = false;
  44499. /**
  44500. * Allows using the bump map in parallax mode.
  44501. */
  44502. _this._useParallax = false;
  44503. /**
  44504. * Allows using the bump map in parallax occlusion mode.
  44505. */
  44506. _this._useParallaxOcclusion = false;
  44507. /**
  44508. * Controls the scale bias of the parallax mode.
  44509. */
  44510. _this._parallaxScaleBias = 0.05;
  44511. /**
  44512. * If sets to true, disables all the lights affecting the material.
  44513. */
  44514. _this._disableLighting = false;
  44515. /**
  44516. * Number of Simultaneous lights allowed on the material.
  44517. */
  44518. _this._maxSimultaneousLights = 4;
  44519. /**
  44520. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  44521. */
  44522. _this._invertNormalMapX = false;
  44523. /**
  44524. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  44525. */
  44526. _this._invertNormalMapY = false;
  44527. /**
  44528. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44529. */
  44530. _this._twoSidedLighting = false;
  44531. /**
  44532. * Defines the alpha limits in alpha test mode.
  44533. */
  44534. _this._alphaCutOff = 0.4;
  44535. /**
  44536. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  44537. */
  44538. _this._forceAlphaTest = false;
  44539. /**
  44540. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44541. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  44542. */
  44543. _this._useAlphaFresnel = false;
  44544. /**
  44545. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44546. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  44547. */
  44548. _this._useLinearAlphaFresnel = false;
  44549. /**
  44550. * The transparency mode of the material.
  44551. */
  44552. _this._transparencyMode = null;
  44553. /**
  44554. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  44555. * from cos thetav and roughness:
  44556. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  44557. */
  44558. _this._environmentBRDFTexture = null;
  44559. /**
  44560. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  44561. */
  44562. _this._forceIrradianceInFragment = false;
  44563. /**
  44564. * Force normal to face away from face.
  44565. */
  44566. _this._forceNormalForward = false;
  44567. /**
  44568. * Enables specular anti aliasing in the PBR shader.
  44569. * It will both interacts on the Geometry for analytical and IBL lighting.
  44570. * It also prefilter the roughness map based on the bump values.
  44571. */
  44572. _this._enableSpecularAntiAliasing = false;
  44573. /**
  44574. * Stores the available render targets.
  44575. */
  44576. _this._renderTargets = new BABYLON.SmartArray(16);
  44577. /**
  44578. * Sets the global ambient color for the material used in lighting calculations.
  44579. */
  44580. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  44581. /**
  44582. * If set to true, no lighting calculations will be applied.
  44583. */
  44584. _this._unlit = false;
  44585. // Setup the default processing configuration to the scene.
  44586. _this._attachImageProcessingConfiguration(null);
  44587. _this.getRenderTargetTextures = function () {
  44588. _this._renderTargets.reset();
  44589. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  44590. _this._renderTargets.push(_this._reflectionTexture);
  44591. }
  44592. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  44593. _this._renderTargets.push(_this._refractionTexture);
  44594. }
  44595. return _this._renderTargets;
  44596. };
  44597. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  44598. return _this;
  44599. }
  44600. /**
  44601. * Attaches a new image processing configuration to the PBR Material.
  44602. * @param configuration
  44603. */
  44604. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  44605. var _this = this;
  44606. if (configuration === this._imageProcessingConfiguration) {
  44607. return;
  44608. }
  44609. // Detaches observer.
  44610. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44611. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44612. }
  44613. // Pick the scene configuration if needed.
  44614. if (!configuration) {
  44615. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  44616. }
  44617. else {
  44618. this._imageProcessingConfiguration = configuration;
  44619. }
  44620. // Attaches observer.
  44621. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  44622. _this._markAllSubMeshesAsImageProcessingDirty();
  44623. });
  44624. };
  44625. /**
  44626. * Gets the name of the material class.
  44627. */
  44628. PBRBaseMaterial.prototype.getClassName = function () {
  44629. return "PBRBaseMaterial";
  44630. };
  44631. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  44632. /**
  44633. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44634. */
  44635. get: function () {
  44636. return this._useLogarithmicDepth;
  44637. },
  44638. /**
  44639. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44640. */
  44641. set: function (value) {
  44642. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  44643. },
  44644. enumerable: true,
  44645. configurable: true
  44646. });
  44647. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  44648. /**
  44649. * Gets the current transparency mode.
  44650. */
  44651. get: function () {
  44652. return this._transparencyMode;
  44653. },
  44654. /**
  44655. * Sets the transparency mode of the material.
  44656. */
  44657. set: function (value) {
  44658. if (this._transparencyMode === value) {
  44659. return;
  44660. }
  44661. this._transparencyMode = value;
  44662. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  44663. this._markAllSubMeshesAsTexturesAndMiscDirty();
  44664. },
  44665. enumerable: true,
  44666. configurable: true
  44667. });
  44668. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  44669. /**
  44670. * Returns true if alpha blending should be disabled.
  44671. */
  44672. get: function () {
  44673. return (this._linkRefractionWithTransparency ||
  44674. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  44675. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44676. },
  44677. enumerable: true,
  44678. configurable: true
  44679. });
  44680. /**
  44681. * Specifies whether or not this material should be rendered in alpha blend mode.
  44682. */
  44683. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  44684. if (this._disableAlphaBlending) {
  44685. return false;
  44686. }
  44687. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  44688. };
  44689. /**
  44690. * Specifies if the mesh will require alpha blending.
  44691. * @param mesh - BJS mesh.
  44692. */
  44693. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  44694. if (this._disableAlphaBlending) {
  44695. return false;
  44696. }
  44697. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  44698. };
  44699. /**
  44700. * Specifies whether or not this material should be rendered in alpha test mode.
  44701. */
  44702. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  44703. if (this._forceAlphaTest) {
  44704. return true;
  44705. }
  44706. if (this._linkRefractionWithTransparency) {
  44707. return false;
  44708. }
  44709. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44710. };
  44711. /**
  44712. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  44713. */
  44714. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  44715. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  44716. };
  44717. /**
  44718. * Gets the texture used for the alpha test.
  44719. */
  44720. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  44721. return this._albedoTexture;
  44722. };
  44723. /**
  44724. * Specifies that the submesh is ready to be used.
  44725. * @param mesh - BJS mesh.
  44726. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  44727. * @param useInstances - Specifies that instances should be used.
  44728. * @returns - boolean indicating that the submesh is ready or not.
  44729. */
  44730. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  44731. if (subMesh.effect && this.isFrozen) {
  44732. if (this._wasPreviouslyReady) {
  44733. return true;
  44734. }
  44735. }
  44736. if (!subMesh._materialDefines) {
  44737. subMesh._materialDefines = new PBRMaterialDefines();
  44738. }
  44739. var defines = subMesh._materialDefines;
  44740. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  44741. if (defines._renderId === this.getScene().getRenderId()) {
  44742. return true;
  44743. }
  44744. }
  44745. var scene = this.getScene();
  44746. var engine = scene.getEngine();
  44747. if (defines._areTexturesDirty) {
  44748. if (scene.texturesEnabled) {
  44749. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44750. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  44751. return false;
  44752. }
  44753. }
  44754. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44755. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  44756. return false;
  44757. }
  44758. }
  44759. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44760. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  44761. return false;
  44762. }
  44763. }
  44764. var reflectionTexture = this._getReflectionTexture();
  44765. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44766. if (!reflectionTexture.isReadyOrNotBlocking()) {
  44767. return false;
  44768. }
  44769. }
  44770. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44771. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  44772. return false;
  44773. }
  44774. }
  44775. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44776. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  44777. return false;
  44778. }
  44779. }
  44780. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44781. if (this._metallicTexture) {
  44782. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  44783. return false;
  44784. }
  44785. }
  44786. else if (this._reflectivityTexture) {
  44787. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  44788. return false;
  44789. }
  44790. }
  44791. if (this._microSurfaceTexture) {
  44792. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  44793. return false;
  44794. }
  44795. }
  44796. }
  44797. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44798. // Bump texture cannot be not blocking.
  44799. if (!this._bumpTexture.isReady()) {
  44800. return false;
  44801. }
  44802. }
  44803. var refractionTexture = this._getRefractionTexture();
  44804. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44805. if (!refractionTexture.isReadyOrNotBlocking()) {
  44806. return false;
  44807. }
  44808. }
  44809. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44810. // This is blocking.
  44811. if (!this._environmentBRDFTexture.isReady()) {
  44812. return false;
  44813. }
  44814. }
  44815. }
  44816. }
  44817. if (defines._areImageProcessingDirty) {
  44818. if (!this._imageProcessingConfiguration.isReady()) {
  44819. return false;
  44820. }
  44821. }
  44822. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  44823. mesh.createNormals(true);
  44824. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  44825. }
  44826. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  44827. if (effect) {
  44828. scene.resetCachedMaterial();
  44829. subMesh.setEffect(effect, defines);
  44830. this.buildUniformLayout();
  44831. }
  44832. if (!subMesh.effect || !subMesh.effect.isReady()) {
  44833. return false;
  44834. }
  44835. defines._renderId = scene.getRenderId();
  44836. this._wasPreviouslyReady = true;
  44837. return true;
  44838. };
  44839. /**
  44840. * Specifies if the material uses metallic roughness workflow.
  44841. * @returns boolean specifiying if the material uses metallic roughness workflow.
  44842. */
  44843. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  44844. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  44845. return true;
  44846. }
  44847. return false;
  44848. };
  44849. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  44850. if (onCompiled === void 0) { onCompiled = null; }
  44851. if (onError === void 0) { onError = null; }
  44852. if (useInstances === void 0) { useInstances = null; }
  44853. if (useClipPlane === void 0) { useClipPlane = null; }
  44854. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  44855. if (!defines.isDirty) {
  44856. return null;
  44857. }
  44858. defines.markAsProcessed();
  44859. var scene = this.getScene();
  44860. var engine = scene.getEngine();
  44861. // Fallbacks
  44862. var fallbacks = new BABYLON.EffectFallbacks();
  44863. var fallbackRank = 0;
  44864. if (defines.USESPHERICALINVERTEX) {
  44865. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  44866. }
  44867. if (defines.FOG) {
  44868. fallbacks.addFallback(fallbackRank, "FOG");
  44869. }
  44870. if (defines.SPECULARAA) {
  44871. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  44872. }
  44873. if (defines.POINTSIZE) {
  44874. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  44875. }
  44876. if (defines.LOGARITHMICDEPTH) {
  44877. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  44878. }
  44879. if (defines.PARALLAX) {
  44880. fallbacks.addFallback(fallbackRank, "PARALLAX");
  44881. }
  44882. if (defines.PARALLAXOCCLUSION) {
  44883. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  44884. }
  44885. if (defines.ENVIRONMENTBRDF) {
  44886. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  44887. }
  44888. if (defines.TANGENT) {
  44889. fallbacks.addFallback(fallbackRank++, "TANGENT");
  44890. }
  44891. if (defines.BUMP) {
  44892. fallbacks.addFallback(fallbackRank++, "BUMP");
  44893. }
  44894. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  44895. if (defines.SPECULARTERM) {
  44896. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  44897. }
  44898. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  44899. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  44900. }
  44901. if (defines.LIGHTMAP) {
  44902. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  44903. }
  44904. if (defines.NORMAL) {
  44905. fallbacks.addFallback(fallbackRank++, "NORMAL");
  44906. }
  44907. if (defines.AMBIENT) {
  44908. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  44909. }
  44910. if (defines.EMISSIVE) {
  44911. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  44912. }
  44913. if (defines.VERTEXCOLOR) {
  44914. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  44915. }
  44916. if (defines.NUM_BONE_INFLUENCERS > 0) {
  44917. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  44918. }
  44919. if (defines.MORPHTARGETS) {
  44920. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  44921. }
  44922. //Attributes
  44923. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44924. if (defines.NORMAL) {
  44925. attribs.push(BABYLON.VertexBuffer.NormalKind);
  44926. }
  44927. if (defines.TANGENT) {
  44928. attribs.push(BABYLON.VertexBuffer.TangentKind);
  44929. }
  44930. if (defines.UV1) {
  44931. attribs.push(BABYLON.VertexBuffer.UVKind);
  44932. }
  44933. if (defines.UV2) {
  44934. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44935. }
  44936. if (defines.VERTEXCOLOR) {
  44937. attribs.push(BABYLON.VertexBuffer.ColorKind);
  44938. }
  44939. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  44940. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  44941. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  44942. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  44943. "vFogInfos", "vFogColor", "pointSize",
  44944. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  44945. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  44946. "mBones",
  44947. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  44948. "vLightingIntensity",
  44949. "logarithmicDepthConstant",
  44950. "vSphericalX", "vSphericalY", "vSphericalZ",
  44951. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  44952. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  44953. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  44954. "vTangentSpaceParams"
  44955. ];
  44956. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  44957. "bumpSampler", "lightmapSampler", "opacitySampler",
  44958. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  44959. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  44960. "microSurfaceSampler", "environmentBrdfSampler"];
  44961. var uniformBuffers = ["Material", "Scene"];
  44962. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  44963. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  44964. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  44965. uniformsNames: uniforms,
  44966. uniformBuffersNames: uniformBuffers,
  44967. samplers: samplers,
  44968. defines: defines,
  44969. maxSimultaneousLights: this._maxSimultaneousLights
  44970. });
  44971. var join = defines.toString();
  44972. return engine.createEffect("pbr", {
  44973. attributes: attribs,
  44974. uniformsNames: uniforms,
  44975. uniformBuffersNames: uniformBuffers,
  44976. samplers: samplers,
  44977. defines: join,
  44978. fallbacks: fallbacks,
  44979. onCompiled: onCompiled,
  44980. onError: onError,
  44981. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  44982. }, engine);
  44983. };
  44984. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  44985. if (useInstances === void 0) { useInstances = null; }
  44986. if (useClipPlane === void 0) { useClipPlane = null; }
  44987. var scene = this.getScene();
  44988. var engine = scene.getEngine();
  44989. // Lights
  44990. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  44991. defines._needNormals = true;
  44992. // Textures
  44993. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  44994. if (defines._areTexturesDirty) {
  44995. defines._needUVs = false;
  44996. if (scene.texturesEnabled) {
  44997. if (scene.getEngine().getCaps().textureLOD) {
  44998. defines.LODBASEDMICROSFURACE = true;
  44999. }
  45000. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45001. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  45002. }
  45003. else {
  45004. defines.ALBEDO = false;
  45005. }
  45006. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45007. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  45008. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  45009. }
  45010. else {
  45011. defines.AMBIENT = false;
  45012. }
  45013. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45014. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  45015. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  45016. }
  45017. else {
  45018. defines.OPACITY = false;
  45019. }
  45020. var reflectionTexture = this._getReflectionTexture();
  45021. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45022. defines.REFLECTION = true;
  45023. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  45024. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  45025. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  45026. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  45027. defines.INVERTCUBICMAP = true;
  45028. }
  45029. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  45030. switch (reflectionTexture.coordinatesMode) {
  45031. case BABYLON.Texture.EXPLICIT_MODE:
  45032. defines.REFLECTIONMAP_EXPLICIT = true;
  45033. break;
  45034. case BABYLON.Texture.PLANAR_MODE:
  45035. defines.REFLECTIONMAP_PLANAR = true;
  45036. break;
  45037. case BABYLON.Texture.PROJECTION_MODE:
  45038. defines.REFLECTIONMAP_PROJECTION = true;
  45039. break;
  45040. case BABYLON.Texture.SKYBOX_MODE:
  45041. defines.REFLECTIONMAP_SKYBOX = true;
  45042. break;
  45043. case BABYLON.Texture.SPHERICAL_MODE:
  45044. defines.REFLECTIONMAP_SPHERICAL = true;
  45045. break;
  45046. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  45047. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  45048. break;
  45049. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  45050. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  45051. break;
  45052. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  45053. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  45054. break;
  45055. case BABYLON.Texture.CUBIC_MODE:
  45056. case BABYLON.Texture.INVCUBIC_MODE:
  45057. default:
  45058. defines.REFLECTIONMAP_CUBIC = true;
  45059. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  45060. break;
  45061. }
  45062. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  45063. if (reflectionTexture.sphericalPolynomial) {
  45064. defines.USESPHERICALFROMREFLECTIONMAP = true;
  45065. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  45066. defines.USESPHERICALINVERTEX = false;
  45067. }
  45068. else {
  45069. defines.USESPHERICALINVERTEX = true;
  45070. }
  45071. }
  45072. }
  45073. }
  45074. else {
  45075. defines.REFLECTION = false;
  45076. defines.REFLECTIONMAP_3D = false;
  45077. defines.REFLECTIONMAP_SPHERICAL = false;
  45078. defines.REFLECTIONMAP_PLANAR = false;
  45079. defines.REFLECTIONMAP_CUBIC = false;
  45080. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  45081. defines.REFLECTIONMAP_PROJECTION = false;
  45082. defines.REFLECTIONMAP_SKYBOX = false;
  45083. defines.REFLECTIONMAP_EXPLICIT = false;
  45084. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  45085. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  45086. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  45087. defines.INVERTCUBICMAP = false;
  45088. defines.USESPHERICALFROMREFLECTIONMAP = false;
  45089. defines.USESPHERICALINVERTEX = false;
  45090. defines.REFLECTIONMAP_OPPOSITEZ = false;
  45091. defines.LODINREFLECTIONALPHA = false;
  45092. defines.GAMMAREFLECTION = false;
  45093. }
  45094. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45095. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  45096. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  45097. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  45098. }
  45099. else {
  45100. defines.LIGHTMAP = false;
  45101. }
  45102. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45103. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  45104. }
  45105. else {
  45106. defines.EMISSIVE = false;
  45107. }
  45108. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45109. if (this._metallicTexture) {
  45110. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  45111. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  45112. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  45113. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  45114. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  45115. }
  45116. else if (this._reflectivityTexture) {
  45117. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  45118. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  45119. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  45120. }
  45121. else {
  45122. defines.REFLECTIVITY = false;
  45123. }
  45124. if (this._microSurfaceTexture) {
  45125. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  45126. }
  45127. else {
  45128. defines.MICROSURFACEMAP = false;
  45129. }
  45130. }
  45131. else {
  45132. defines.REFLECTIVITY = false;
  45133. defines.MICROSURFACEMAP = false;
  45134. }
  45135. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45136. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  45137. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45138. defines.PARALLAX = true;
  45139. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  45140. }
  45141. else {
  45142. defines.PARALLAX = false;
  45143. }
  45144. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  45145. }
  45146. else {
  45147. defines.BUMP = false;
  45148. }
  45149. var refractionTexture = this._getRefractionTexture();
  45150. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45151. defines.REFRACTION = true;
  45152. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  45153. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  45154. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  45155. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  45156. if (this._linkRefractionWithTransparency) {
  45157. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  45158. }
  45159. }
  45160. else {
  45161. defines.REFRACTION = false;
  45162. }
  45163. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45164. defines.ENVIRONMENTBRDF = true;
  45165. }
  45166. else {
  45167. defines.ENVIRONMENTBRDF = false;
  45168. }
  45169. if (this._shouldUseAlphaFromAlbedoTexture()) {
  45170. defines.ALPHAFROMALBEDO = true;
  45171. }
  45172. else {
  45173. defines.ALPHAFROMALBEDO = false;
  45174. }
  45175. }
  45176. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  45177. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  45178. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  45179. if (!this.backFaceCulling && this._twoSidedLighting) {
  45180. defines.TWOSIDEDLIGHTING = true;
  45181. }
  45182. else {
  45183. defines.TWOSIDEDLIGHTING = false;
  45184. }
  45185. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  45186. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  45187. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  45188. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  45189. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  45190. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  45191. }
  45192. if (defines._areImageProcessingDirty) {
  45193. this._imageProcessingConfiguration.prepareDefines(defines);
  45194. }
  45195. defines.FORCENORMALFORWARD = this._forceNormalForward;
  45196. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  45197. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  45198. // Misc.
  45199. if (defines._areMiscDirty) {
  45200. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  45201. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  45202. }
  45203. // Values that need to be evaluated on every frame
  45204. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  45205. // Attribs
  45206. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  45207. };
  45208. /**
  45209. * Force shader compilation
  45210. */
  45211. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  45212. var _this = this;
  45213. var localOptions = __assign({ clipPlane: false }, options);
  45214. var defines = new PBRMaterialDefines();
  45215. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  45216. if (effect.isReady()) {
  45217. if (onCompiled) {
  45218. onCompiled(this);
  45219. }
  45220. }
  45221. else {
  45222. effect.onCompileObservable.add(function () {
  45223. if (onCompiled) {
  45224. onCompiled(_this);
  45225. }
  45226. });
  45227. }
  45228. };
  45229. /**
  45230. * Initializes the uniform buffer layout for the shader.
  45231. */
  45232. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  45233. // Order is important !
  45234. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  45235. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  45236. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  45237. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  45238. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  45239. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  45240. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  45241. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  45242. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  45243. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  45244. this._uniformBuffer.addUniform("vReflectionSize", 3);
  45245. this._uniformBuffer.addUniform("vBumpInfos", 3);
  45246. this._uniformBuffer.addUniform("albedoMatrix", 16);
  45247. this._uniformBuffer.addUniform("ambientMatrix", 16);
  45248. this._uniformBuffer.addUniform("opacityMatrix", 16);
  45249. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  45250. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  45251. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  45252. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  45253. this._uniformBuffer.addUniform("bumpMatrix", 16);
  45254. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  45255. this._uniformBuffer.addUniform("refractionMatrix", 16);
  45256. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  45257. this._uniformBuffer.addUniform("vReflectionColor", 3);
  45258. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  45259. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  45260. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  45261. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  45262. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  45263. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  45264. this._uniformBuffer.addUniform("pointSize", 1);
  45265. this._uniformBuffer.create();
  45266. };
  45267. /**
  45268. * Unbinds the textures.
  45269. */
  45270. PBRBaseMaterial.prototype.unbind = function () {
  45271. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  45272. this._uniformBuffer.setTexture("reflectionSampler", null);
  45273. }
  45274. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  45275. this._uniformBuffer.setTexture("refractionSampler", null);
  45276. }
  45277. _super.prototype.unbind.call(this);
  45278. };
  45279. /**
  45280. * Binds the submesh data.
  45281. * @param world - The world matrix.
  45282. * @param mesh - The BJS mesh.
  45283. * @param subMesh - A submesh of the BJS mesh.
  45284. */
  45285. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  45286. var scene = this.getScene();
  45287. var defines = subMesh._materialDefines;
  45288. if (!defines) {
  45289. return;
  45290. }
  45291. var effect = subMesh.effect;
  45292. if (!effect) {
  45293. return;
  45294. }
  45295. this._activeEffect = effect;
  45296. // Matrices
  45297. this.bindOnlyWorldMatrix(world);
  45298. // Normal Matrix
  45299. if (defines.OBJECTSPACE_NORMALMAP) {
  45300. world.toNormalMatrix(this._normalMatrix);
  45301. this.bindOnlyNormalMatrix(this._normalMatrix);
  45302. }
  45303. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  45304. // Bones
  45305. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  45306. var reflectionTexture = null;
  45307. if (mustRebind) {
  45308. this._uniformBuffer.bindToEffect(effect, "Material");
  45309. this.bindViewProjection(effect);
  45310. reflectionTexture = this._getReflectionTexture();
  45311. var refractionTexture = this._getRefractionTexture();
  45312. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  45313. // Texture uniforms
  45314. if (scene.texturesEnabled) {
  45315. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45316. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  45317. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  45318. }
  45319. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45320. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  45321. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  45322. }
  45323. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45324. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  45325. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  45326. }
  45327. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45328. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  45329. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  45330. if (reflectionTexture.boundingBoxSize) {
  45331. var cubeTexture = reflectionTexture;
  45332. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  45333. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  45334. }
  45335. var polynomials = reflectionTexture.sphericalPolynomial;
  45336. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  45337. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  45338. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  45339. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  45340. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  45341. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  45342. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  45343. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  45344. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  45345. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  45346. }
  45347. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  45348. }
  45349. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45350. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  45351. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  45352. }
  45353. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45354. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  45355. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  45356. }
  45357. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45358. if (this._metallicTexture) {
  45359. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  45360. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  45361. }
  45362. else if (this._reflectivityTexture) {
  45363. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  45364. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  45365. }
  45366. if (this._microSurfaceTexture) {
  45367. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  45368. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  45369. }
  45370. }
  45371. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45372. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  45373. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  45374. if (scene._mirroredCameraPosition) {
  45375. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  45376. }
  45377. else {
  45378. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  45379. }
  45380. }
  45381. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45382. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  45383. var depth = 1.0;
  45384. if (!refractionTexture.isCube) {
  45385. if (refractionTexture.depth) {
  45386. depth = refractionTexture.depth;
  45387. }
  45388. }
  45389. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  45390. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  45391. }
  45392. }
  45393. // Point size
  45394. if (this.pointsCloud) {
  45395. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  45396. }
  45397. // Colors
  45398. if (defines.METALLICWORKFLOW) {
  45399. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  45400. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  45401. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  45402. }
  45403. else {
  45404. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  45405. }
  45406. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  45407. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  45408. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  45409. // Misc
  45410. this._lightingInfos.x = this._directIntensity;
  45411. this._lightingInfos.y = this._emissiveIntensity;
  45412. this._lightingInfos.z = this._environmentIntensity;
  45413. this._lightingInfos.w = this._specularIntensity;
  45414. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  45415. }
  45416. // Textures
  45417. if (scene.texturesEnabled) {
  45418. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45419. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  45420. }
  45421. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45422. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  45423. }
  45424. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45425. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  45426. }
  45427. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45428. if (defines.LODBASEDMICROSFURACE) {
  45429. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  45430. }
  45431. else {
  45432. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  45433. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  45434. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  45435. }
  45436. }
  45437. if (defines.ENVIRONMENTBRDF) {
  45438. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  45439. }
  45440. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45441. if (defines.LODBASEDMICROSFURACE) {
  45442. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  45443. }
  45444. else {
  45445. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  45446. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  45447. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  45448. }
  45449. }
  45450. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45451. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  45452. }
  45453. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45454. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  45455. }
  45456. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45457. if (this._metallicTexture) {
  45458. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  45459. }
  45460. else if (this._reflectivityTexture) {
  45461. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  45462. }
  45463. if (this._microSurfaceTexture) {
  45464. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  45465. }
  45466. }
  45467. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45468. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  45469. }
  45470. }
  45471. // Clip plane
  45472. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  45473. // Colors
  45474. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  45475. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  45476. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  45477. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  45478. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  45479. }
  45480. if (mustRebind || !this.isFrozen) {
  45481. // Lights
  45482. if (scene.lightsEnabled && !this._disableLighting) {
  45483. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  45484. }
  45485. // View
  45486. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  45487. this.bindView(effect);
  45488. }
  45489. // Fog
  45490. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  45491. // Morph targets
  45492. if (defines.NUM_MORPH_INFLUENCERS) {
  45493. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  45494. }
  45495. // image processing
  45496. this._imageProcessingConfiguration.bind(this._activeEffect);
  45497. // Log. depth
  45498. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  45499. }
  45500. this._uniformBuffer.update();
  45501. this._afterBind(mesh, this._activeEffect);
  45502. };
  45503. /**
  45504. * Returns the animatable textures.
  45505. * @returns - Array of animatable textures.
  45506. */
  45507. PBRBaseMaterial.prototype.getAnimatables = function () {
  45508. var results = [];
  45509. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  45510. results.push(this._albedoTexture);
  45511. }
  45512. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  45513. results.push(this._ambientTexture);
  45514. }
  45515. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  45516. results.push(this._opacityTexture);
  45517. }
  45518. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  45519. results.push(this._reflectionTexture);
  45520. }
  45521. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  45522. results.push(this._emissiveTexture);
  45523. }
  45524. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  45525. results.push(this._metallicTexture);
  45526. }
  45527. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  45528. results.push(this._reflectivityTexture);
  45529. }
  45530. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  45531. results.push(this._bumpTexture);
  45532. }
  45533. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  45534. results.push(this._lightmapTexture);
  45535. }
  45536. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  45537. results.push(this._refractionTexture);
  45538. }
  45539. return results;
  45540. };
  45541. /**
  45542. * Returns the texture used for reflections.
  45543. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  45544. */
  45545. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  45546. if (this._reflectionTexture) {
  45547. return this._reflectionTexture;
  45548. }
  45549. return this.getScene().environmentTexture;
  45550. };
  45551. /**
  45552. * Returns the texture used for refraction or null if none is used.
  45553. * @returns - Refection texture if present. If no refraction texture and refraction
  45554. * is linked with transparency, returns environment texture. Otherwise, returns null.
  45555. */
  45556. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  45557. if (this._refractionTexture) {
  45558. return this._refractionTexture;
  45559. }
  45560. if (this._linkRefractionWithTransparency) {
  45561. return this.getScene().environmentTexture;
  45562. }
  45563. return null;
  45564. };
  45565. /**
  45566. * Disposes the resources of the material.
  45567. * @param forceDisposeEffect - Forces the disposal of effects.
  45568. * @param forceDisposeTextures - Forces the disposal of all textures.
  45569. */
  45570. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  45571. if (forceDisposeTextures) {
  45572. if (this._albedoTexture) {
  45573. this._albedoTexture.dispose();
  45574. }
  45575. if (this._ambientTexture) {
  45576. this._ambientTexture.dispose();
  45577. }
  45578. if (this._opacityTexture) {
  45579. this._opacityTexture.dispose();
  45580. }
  45581. if (this._reflectionTexture) {
  45582. this._reflectionTexture.dispose();
  45583. }
  45584. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  45585. this._environmentBRDFTexture.dispose();
  45586. }
  45587. if (this._emissiveTexture) {
  45588. this._emissiveTexture.dispose();
  45589. }
  45590. if (this._metallicTexture) {
  45591. this._metallicTexture.dispose();
  45592. }
  45593. if (this._reflectivityTexture) {
  45594. this._reflectivityTexture.dispose();
  45595. }
  45596. if (this._bumpTexture) {
  45597. this._bumpTexture.dispose();
  45598. }
  45599. if (this._lightmapTexture) {
  45600. this._lightmapTexture.dispose();
  45601. }
  45602. if (this._refractionTexture) {
  45603. this._refractionTexture.dispose();
  45604. }
  45605. }
  45606. this._renderTargets.dispose();
  45607. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  45608. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  45609. }
  45610. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  45611. };
  45612. /**
  45613. * Stores the reflectivity values based on metallic roughness workflow.
  45614. */
  45615. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  45616. __decorate([
  45617. BABYLON.serializeAsImageProcessingConfiguration()
  45618. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  45619. __decorate([
  45620. BABYLON.serialize()
  45621. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  45622. __decorate([
  45623. BABYLON.serialize()
  45624. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  45625. return PBRBaseMaterial;
  45626. }(BABYLON.PushMaterial));
  45627. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  45628. })(BABYLON || (BABYLON = {}));
  45629. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  45630. var BABYLON;
  45631. (function (BABYLON) {
  45632. /**
  45633. * The Physically based simple base material of BJS.
  45634. *
  45635. * This enables better naming and convention enforcements on top of the pbrMaterial.
  45636. * It is used as the base class for both the specGloss and metalRough conventions.
  45637. */
  45638. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  45639. __extends(PBRBaseSimpleMaterial, _super);
  45640. /**
  45641. * Instantiates a new PBRMaterial instance.
  45642. *
  45643. * @param name The material name
  45644. * @param scene The scene the material will be use in.
  45645. */
  45646. function PBRBaseSimpleMaterial(name, scene) {
  45647. var _this = _super.call(this, name, scene) || this;
  45648. /**
  45649. * Number of Simultaneous lights allowed on the material.
  45650. */
  45651. _this.maxSimultaneousLights = 4;
  45652. /**
  45653. * If sets to true, disables all the lights affecting the material.
  45654. */
  45655. _this.disableLighting = false;
  45656. /**
  45657. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45658. */
  45659. _this.invertNormalMapX = false;
  45660. /**
  45661. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45662. */
  45663. _this.invertNormalMapY = false;
  45664. /**
  45665. * Emissivie color used to self-illuminate the model.
  45666. */
  45667. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45668. /**
  45669. * Occlusion Channel Strenght.
  45670. */
  45671. _this.occlusionStrength = 1.0;
  45672. _this.useLightmapAsShadowmap = false;
  45673. _this._useAlphaFromAlbedoTexture = true;
  45674. _this._useAmbientInGrayScale = true;
  45675. return _this;
  45676. }
  45677. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  45678. /**
  45679. * Gets the current double sided mode.
  45680. */
  45681. get: function () {
  45682. return this._twoSidedLighting;
  45683. },
  45684. /**
  45685. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45686. */
  45687. set: function (value) {
  45688. if (this._twoSidedLighting === value) {
  45689. return;
  45690. }
  45691. this._twoSidedLighting = value;
  45692. this.backFaceCulling = !value;
  45693. this._markAllSubMeshesAsTexturesDirty();
  45694. },
  45695. enumerable: true,
  45696. configurable: true
  45697. });
  45698. /**
  45699. * Return the active textures of the material.
  45700. */
  45701. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  45702. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45703. if (this.environmentTexture) {
  45704. activeTextures.push(this.environmentTexture);
  45705. }
  45706. if (this.normalTexture) {
  45707. activeTextures.push(this.normalTexture);
  45708. }
  45709. if (this.emissiveTexture) {
  45710. activeTextures.push(this.emissiveTexture);
  45711. }
  45712. if (this.occlusionTexture) {
  45713. activeTextures.push(this.occlusionTexture);
  45714. }
  45715. if (this.lightmapTexture) {
  45716. activeTextures.push(this.lightmapTexture);
  45717. }
  45718. return activeTextures;
  45719. };
  45720. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  45721. if (_super.prototype.hasTexture.call(this, texture)) {
  45722. return true;
  45723. }
  45724. if (this.lightmapTexture === texture) {
  45725. return true;
  45726. }
  45727. return false;
  45728. };
  45729. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  45730. return "PBRBaseSimpleMaterial";
  45731. };
  45732. __decorate([
  45733. BABYLON.serialize(),
  45734. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45735. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  45736. __decorate([
  45737. BABYLON.serialize(),
  45738. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45739. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  45740. __decorate([
  45741. BABYLON.serializeAsTexture(),
  45742. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  45743. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  45744. __decorate([
  45745. BABYLON.serialize(),
  45746. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45747. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  45748. __decorate([
  45749. BABYLON.serialize(),
  45750. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45751. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  45752. __decorate([
  45753. BABYLON.serializeAsTexture(),
  45754. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  45755. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  45756. __decorate([
  45757. BABYLON.serializeAsColor3("emissive"),
  45758. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45759. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  45760. __decorate([
  45761. BABYLON.serializeAsTexture(),
  45762. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45763. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  45764. __decorate([
  45765. BABYLON.serialize(),
  45766. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  45767. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  45768. __decorate([
  45769. BABYLON.serializeAsTexture(),
  45770. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  45771. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  45772. __decorate([
  45773. BABYLON.serialize(),
  45774. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  45775. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  45776. __decorate([
  45777. BABYLON.serialize()
  45778. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  45779. __decorate([
  45780. BABYLON.serializeAsTexture(),
  45781. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45782. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  45783. __decorate([
  45784. BABYLON.serialize(),
  45785. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45786. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45787. return PBRBaseSimpleMaterial;
  45788. }(BABYLON.PBRBaseMaterial));
  45789. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  45790. })(BABYLON || (BABYLON = {}));
  45791. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  45792. var BABYLON;
  45793. (function (BABYLON) {
  45794. /**
  45795. * The Physically based material of BJS.
  45796. *
  45797. * This offers the main features of a standard PBR material.
  45798. * For more information, please refer to the documentation :
  45799. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  45800. */
  45801. var PBRMaterial = /** @class */ (function (_super) {
  45802. __extends(PBRMaterial, _super);
  45803. /**
  45804. * Instantiates a new PBRMaterial instance.
  45805. *
  45806. * @param name The material name
  45807. * @param scene The scene the material will be use in.
  45808. */
  45809. function PBRMaterial(name, scene) {
  45810. var _this = _super.call(this, name, scene) || this;
  45811. /**
  45812. * Intensity of the direct lights e.g. the four lights available in your scene.
  45813. * This impacts both the direct diffuse and specular highlights.
  45814. */
  45815. _this.directIntensity = 1.0;
  45816. /**
  45817. * Intensity of the emissive part of the material.
  45818. * This helps controlling the emissive effect without modifying the emissive color.
  45819. */
  45820. _this.emissiveIntensity = 1.0;
  45821. /**
  45822. * Intensity of the environment e.g. how much the environment will light the object
  45823. * either through harmonics for rough material or through the refelction for shiny ones.
  45824. */
  45825. _this.environmentIntensity = 1.0;
  45826. /**
  45827. * This is a special control allowing the reduction of the specular highlights coming from the
  45828. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  45829. */
  45830. _this.specularIntensity = 1.0;
  45831. /**
  45832. * Debug Control allowing disabling the bump map on this material.
  45833. */
  45834. _this.disableBumpMap = false;
  45835. /**
  45836. * AKA Occlusion Texture Intensity in other nomenclature.
  45837. */
  45838. _this.ambientTextureStrength = 1.0;
  45839. /**
  45840. * The color of a material in ambient lighting.
  45841. */
  45842. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  45843. /**
  45844. * AKA Diffuse Color in other nomenclature.
  45845. */
  45846. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  45847. /**
  45848. * AKA Specular Color in other nomenclature.
  45849. */
  45850. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  45851. /**
  45852. * The color reflected from the material.
  45853. */
  45854. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  45855. /**
  45856. * The color emitted from the material.
  45857. */
  45858. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45859. /**
  45860. * AKA Glossiness in other nomenclature.
  45861. */
  45862. _this.microSurface = 1.0;
  45863. /**
  45864. * source material index of refraction (IOR)' / 'destination material IOR.
  45865. */
  45866. _this.indexOfRefraction = 0.66;
  45867. /**
  45868. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  45869. */
  45870. _this.invertRefractionY = false;
  45871. /**
  45872. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  45873. * Materials half opaque for instance using refraction could benefit from this control.
  45874. */
  45875. _this.linkRefractionWithTransparency = false;
  45876. _this.useLightmapAsShadowmap = false;
  45877. /**
  45878. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  45879. */
  45880. _this.useAlphaFromAlbedoTexture = false;
  45881. /**
  45882. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  45883. */
  45884. _this.forceAlphaTest = false;
  45885. /**
  45886. * Defines the alpha limits in alpha test mode.
  45887. */
  45888. _this.alphaCutOff = 0.4;
  45889. /**
  45890. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  45891. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  45892. */
  45893. _this.useSpecularOverAlpha = true;
  45894. /**
  45895. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  45896. */
  45897. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  45898. /**
  45899. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  45900. */
  45901. _this.useRoughnessFromMetallicTextureAlpha = true;
  45902. /**
  45903. * Specifies if the metallic texture contains the roughness information in its green channel.
  45904. */
  45905. _this.useRoughnessFromMetallicTextureGreen = false;
  45906. /**
  45907. * Specifies if the metallic texture contains the metallness information in its blue channel.
  45908. */
  45909. _this.useMetallnessFromMetallicTextureBlue = false;
  45910. /**
  45911. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  45912. */
  45913. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  45914. /**
  45915. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  45916. */
  45917. _this.useAmbientInGrayScale = false;
  45918. /**
  45919. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  45920. * The material will try to infer what glossiness each pixel should be.
  45921. */
  45922. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  45923. /**
  45924. * BJS is using an harcoded light falloff based on a manually sets up range.
  45925. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45926. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45927. */
  45928. _this.usePhysicalLightFalloff = true;
  45929. /**
  45930. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  45931. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  45932. */
  45933. _this.useRadianceOverAlpha = true;
  45934. /**
  45935. * Allows using an object space normal map (instead of tangent space).
  45936. */
  45937. _this.useObjectSpaceNormalMap = false;
  45938. /**
  45939. * Allows using the bump map in parallax mode.
  45940. */
  45941. _this.useParallax = false;
  45942. /**
  45943. * Allows using the bump map in parallax occlusion mode.
  45944. */
  45945. _this.useParallaxOcclusion = false;
  45946. /**
  45947. * Controls the scale bias of the parallax mode.
  45948. */
  45949. _this.parallaxScaleBias = 0.05;
  45950. /**
  45951. * If sets to true, disables all the lights affecting the material.
  45952. */
  45953. _this.disableLighting = false;
  45954. /**
  45955. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  45956. */
  45957. _this.forceIrradianceInFragment = false;
  45958. /**
  45959. * Number of Simultaneous lights allowed on the material.
  45960. */
  45961. _this.maxSimultaneousLights = 4;
  45962. /**
  45963. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45964. */
  45965. _this.invertNormalMapX = false;
  45966. /**
  45967. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45968. */
  45969. _this.invertNormalMapY = false;
  45970. /**
  45971. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45972. */
  45973. _this.twoSidedLighting = false;
  45974. /**
  45975. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45976. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  45977. */
  45978. _this.useAlphaFresnel = false;
  45979. /**
  45980. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45981. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  45982. */
  45983. _this.useLinearAlphaFresnel = false;
  45984. /**
  45985. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45986. * And/Or occlude the blended part.
  45987. */
  45988. _this.environmentBRDFTexture = null;
  45989. /**
  45990. * Force normal to face away from face.
  45991. */
  45992. _this.forceNormalForward = false;
  45993. /**
  45994. * Enables specular anti aliasing in the PBR shader.
  45995. * It will both interacts on the Geometry for analytical and IBL lighting.
  45996. * It also prefilter the roughness map based on the bump values.
  45997. */
  45998. _this.enableSpecularAntiAliasing = false;
  45999. /**
  46000. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  46001. * makes the reflect vector face the model (under horizon).
  46002. */
  46003. _this.useHorizonOcclusion = true;
  46004. /**
  46005. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  46006. * too much the area relying on ambient texture to define their ambient occlusion.
  46007. */
  46008. _this.useRadianceOcclusion = true;
  46009. /**
  46010. * If set to true, no lighting calculations will be applied.
  46011. */
  46012. _this.unlit = false;
  46013. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  46014. return _this;
  46015. }
  46016. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  46017. /**
  46018. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  46019. */
  46020. get: function () {
  46021. return this._PBRMATERIAL_OPAQUE;
  46022. },
  46023. enumerable: true,
  46024. configurable: true
  46025. });
  46026. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  46027. /**
  46028. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  46029. */
  46030. get: function () {
  46031. return this._PBRMATERIAL_ALPHATEST;
  46032. },
  46033. enumerable: true,
  46034. configurable: true
  46035. });
  46036. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  46037. /**
  46038. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46039. */
  46040. get: function () {
  46041. return this._PBRMATERIAL_ALPHABLEND;
  46042. },
  46043. enumerable: true,
  46044. configurable: true
  46045. });
  46046. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  46047. /**
  46048. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46049. * They are also discarded below the alpha cutoff threshold to improve performances.
  46050. */
  46051. get: function () {
  46052. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  46053. },
  46054. enumerable: true,
  46055. configurable: true
  46056. });
  46057. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  46058. /**
  46059. * Gets the image processing configuration used either in this material.
  46060. */
  46061. get: function () {
  46062. return this._imageProcessingConfiguration;
  46063. },
  46064. /**
  46065. * Sets the Default image processing configuration used either in the this material.
  46066. *
  46067. * If sets to null, the scene one is in use.
  46068. */
  46069. set: function (value) {
  46070. this._attachImageProcessingConfiguration(value);
  46071. // Ensure the effect will be rebuilt.
  46072. this._markAllSubMeshesAsTexturesDirty();
  46073. },
  46074. enumerable: true,
  46075. configurable: true
  46076. });
  46077. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  46078. /**
  46079. * Gets wether the color curves effect is enabled.
  46080. */
  46081. get: function () {
  46082. return this.imageProcessingConfiguration.colorCurvesEnabled;
  46083. },
  46084. /**
  46085. * Sets wether the color curves effect is enabled.
  46086. */
  46087. set: function (value) {
  46088. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  46089. },
  46090. enumerable: true,
  46091. configurable: true
  46092. });
  46093. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  46094. /**
  46095. * Gets wether the color grading effect is enabled.
  46096. */
  46097. get: function () {
  46098. return this.imageProcessingConfiguration.colorGradingEnabled;
  46099. },
  46100. /**
  46101. * Gets wether the color grading effect is enabled.
  46102. */
  46103. set: function (value) {
  46104. this.imageProcessingConfiguration.colorGradingEnabled = value;
  46105. },
  46106. enumerable: true,
  46107. configurable: true
  46108. });
  46109. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  46110. /**
  46111. * Gets wether tonemapping is enabled or not.
  46112. */
  46113. get: function () {
  46114. return this._imageProcessingConfiguration.toneMappingEnabled;
  46115. },
  46116. /**
  46117. * Sets wether tonemapping is enabled or not
  46118. */
  46119. set: function (value) {
  46120. this._imageProcessingConfiguration.toneMappingEnabled = value;
  46121. },
  46122. enumerable: true,
  46123. configurable: true
  46124. });
  46125. ;
  46126. ;
  46127. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  46128. /**
  46129. * The camera exposure used on this material.
  46130. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  46131. * This corresponds to a photographic exposure.
  46132. */
  46133. get: function () {
  46134. return this._imageProcessingConfiguration.exposure;
  46135. },
  46136. /**
  46137. * The camera exposure used on this material.
  46138. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  46139. * This corresponds to a photographic exposure.
  46140. */
  46141. set: function (value) {
  46142. this._imageProcessingConfiguration.exposure = value;
  46143. },
  46144. enumerable: true,
  46145. configurable: true
  46146. });
  46147. ;
  46148. ;
  46149. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  46150. /**
  46151. * Gets The camera contrast used on this material.
  46152. */
  46153. get: function () {
  46154. return this._imageProcessingConfiguration.contrast;
  46155. },
  46156. /**
  46157. * Sets The camera contrast used on this material.
  46158. */
  46159. set: function (value) {
  46160. this._imageProcessingConfiguration.contrast = value;
  46161. },
  46162. enumerable: true,
  46163. configurable: true
  46164. });
  46165. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  46166. /**
  46167. * Gets the Color Grading 2D Lookup Texture.
  46168. */
  46169. get: function () {
  46170. return this._imageProcessingConfiguration.colorGradingTexture;
  46171. },
  46172. /**
  46173. * Sets the Color Grading 2D Lookup Texture.
  46174. */
  46175. set: function (value) {
  46176. this._imageProcessingConfiguration.colorGradingTexture = value;
  46177. },
  46178. enumerable: true,
  46179. configurable: true
  46180. });
  46181. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  46182. /**
  46183. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  46184. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  46185. * 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;
  46186. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  46187. */
  46188. get: function () {
  46189. return this._imageProcessingConfiguration.colorCurves;
  46190. },
  46191. /**
  46192. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  46193. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  46194. * 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;
  46195. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  46196. */
  46197. set: function (value) {
  46198. this._imageProcessingConfiguration.colorCurves = value;
  46199. },
  46200. enumerable: true,
  46201. configurable: true
  46202. });
  46203. /**
  46204. * Returns the name of this material class.
  46205. */
  46206. PBRMaterial.prototype.getClassName = function () {
  46207. return "PBRMaterial";
  46208. };
  46209. /**
  46210. * Returns an array of the actively used textures.
  46211. * @returns - Array of BaseTextures
  46212. */
  46213. PBRMaterial.prototype.getActiveTextures = function () {
  46214. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46215. if (this._albedoTexture) {
  46216. activeTextures.push(this._albedoTexture);
  46217. }
  46218. if (this._ambientTexture) {
  46219. activeTextures.push(this._ambientTexture);
  46220. }
  46221. if (this._opacityTexture) {
  46222. activeTextures.push(this._opacityTexture);
  46223. }
  46224. if (this._reflectionTexture) {
  46225. activeTextures.push(this._reflectionTexture);
  46226. }
  46227. if (this._emissiveTexture) {
  46228. activeTextures.push(this._emissiveTexture);
  46229. }
  46230. if (this._reflectivityTexture) {
  46231. activeTextures.push(this._reflectivityTexture);
  46232. }
  46233. if (this._metallicTexture) {
  46234. activeTextures.push(this._metallicTexture);
  46235. }
  46236. if (this._microSurfaceTexture) {
  46237. activeTextures.push(this._microSurfaceTexture);
  46238. }
  46239. if (this._bumpTexture) {
  46240. activeTextures.push(this._bumpTexture);
  46241. }
  46242. if (this._lightmapTexture) {
  46243. activeTextures.push(this._lightmapTexture);
  46244. }
  46245. if (this._refractionTexture) {
  46246. activeTextures.push(this._refractionTexture);
  46247. }
  46248. return activeTextures;
  46249. };
  46250. /**
  46251. * Checks to see if a texture is used in the material.
  46252. * @param texture - Base texture to use.
  46253. * @returns - Boolean specifying if a texture is used in the material.
  46254. */
  46255. PBRMaterial.prototype.hasTexture = function (texture) {
  46256. if (_super.prototype.hasTexture.call(this, texture)) {
  46257. return true;
  46258. }
  46259. if (this._albedoTexture === texture) {
  46260. return true;
  46261. }
  46262. if (this._ambientTexture === texture) {
  46263. return true;
  46264. }
  46265. if (this._opacityTexture === texture) {
  46266. return true;
  46267. }
  46268. if (this._reflectionTexture === texture) {
  46269. return true;
  46270. }
  46271. if (this._reflectivityTexture === texture) {
  46272. return true;
  46273. }
  46274. if (this._metallicTexture === texture) {
  46275. return true;
  46276. }
  46277. if (this._microSurfaceTexture === texture) {
  46278. return true;
  46279. }
  46280. if (this._bumpTexture === texture) {
  46281. return true;
  46282. }
  46283. if (this._lightmapTexture === texture) {
  46284. return true;
  46285. }
  46286. if (this._refractionTexture === texture) {
  46287. return true;
  46288. }
  46289. return false;
  46290. };
  46291. /**
  46292. * Makes a duplicate of the current material.
  46293. * @param name - name to use for the new material.
  46294. */
  46295. PBRMaterial.prototype.clone = function (name) {
  46296. var _this = this;
  46297. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  46298. clone.id = name;
  46299. clone.name = name;
  46300. return clone;
  46301. };
  46302. /**
  46303. * Serializes this PBR Material.
  46304. * @returns - An object with the serialized material.
  46305. */
  46306. PBRMaterial.prototype.serialize = function () {
  46307. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46308. serializationObject.customType = "BABYLON.PBRMaterial";
  46309. return serializationObject;
  46310. };
  46311. // Statics
  46312. /**
  46313. * Parses a PBR Material from a serialized object.
  46314. * @param source - Serialized object.
  46315. * @param scene - BJS scene instance.
  46316. * @param rootUrl - url for the scene object
  46317. * @returns - PBRMaterial
  46318. */
  46319. PBRMaterial.Parse = function (source, scene, rootUrl) {
  46320. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  46321. };
  46322. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  46323. /**
  46324. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  46325. */
  46326. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  46327. /**
  46328. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46329. */
  46330. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  46331. /**
  46332. * 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.
  46333. * They are also discarded below the alpha cutoff threshold to improve performances.
  46334. */
  46335. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  46336. __decorate([
  46337. BABYLON.serialize(),
  46338. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46339. ], PBRMaterial.prototype, "directIntensity", void 0);
  46340. __decorate([
  46341. BABYLON.serialize(),
  46342. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46343. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  46344. __decorate([
  46345. BABYLON.serialize(),
  46346. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46347. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  46348. __decorate([
  46349. BABYLON.serialize(),
  46350. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46351. ], PBRMaterial.prototype, "specularIntensity", void 0);
  46352. __decorate([
  46353. BABYLON.serialize(),
  46354. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46355. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  46356. __decorate([
  46357. BABYLON.serializeAsTexture(),
  46358. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46359. ], PBRMaterial.prototype, "albedoTexture", void 0);
  46360. __decorate([
  46361. BABYLON.serializeAsTexture(),
  46362. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46363. ], PBRMaterial.prototype, "ambientTexture", void 0);
  46364. __decorate([
  46365. BABYLON.serialize(),
  46366. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46367. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  46368. __decorate([
  46369. BABYLON.serializeAsTexture(),
  46370. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46371. ], PBRMaterial.prototype, "opacityTexture", void 0);
  46372. __decorate([
  46373. BABYLON.serializeAsTexture(),
  46374. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46375. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  46376. __decorate([
  46377. BABYLON.serializeAsTexture(),
  46378. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46379. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  46380. __decorate([
  46381. BABYLON.serializeAsTexture(),
  46382. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46383. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  46384. __decorate([
  46385. BABYLON.serializeAsTexture(),
  46386. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46387. ], PBRMaterial.prototype, "metallicTexture", void 0);
  46388. __decorate([
  46389. BABYLON.serialize(),
  46390. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46391. ], PBRMaterial.prototype, "metallic", void 0);
  46392. __decorate([
  46393. BABYLON.serialize(),
  46394. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46395. ], PBRMaterial.prototype, "roughness", void 0);
  46396. __decorate([
  46397. BABYLON.serializeAsTexture(),
  46398. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46399. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  46400. __decorate([
  46401. BABYLON.serializeAsTexture(),
  46402. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46403. ], PBRMaterial.prototype, "bumpTexture", void 0);
  46404. __decorate([
  46405. BABYLON.serializeAsTexture(),
  46406. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  46407. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  46408. __decorate([
  46409. BABYLON.serializeAsTexture(),
  46410. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46411. ], PBRMaterial.prototype, "refractionTexture", void 0);
  46412. __decorate([
  46413. BABYLON.serializeAsColor3("ambient"),
  46414. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46415. ], PBRMaterial.prototype, "ambientColor", void 0);
  46416. __decorate([
  46417. BABYLON.serializeAsColor3("albedo"),
  46418. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46419. ], PBRMaterial.prototype, "albedoColor", void 0);
  46420. __decorate([
  46421. BABYLON.serializeAsColor3("reflectivity"),
  46422. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46423. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  46424. __decorate([
  46425. BABYLON.serializeAsColor3("reflection"),
  46426. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46427. ], PBRMaterial.prototype, "reflectionColor", void 0);
  46428. __decorate([
  46429. BABYLON.serializeAsColor3("emissive"),
  46430. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46431. ], PBRMaterial.prototype, "emissiveColor", void 0);
  46432. __decorate([
  46433. BABYLON.serialize(),
  46434. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46435. ], PBRMaterial.prototype, "microSurface", void 0);
  46436. __decorate([
  46437. BABYLON.serialize(),
  46438. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46439. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  46440. __decorate([
  46441. BABYLON.serialize(),
  46442. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46443. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  46444. __decorate([
  46445. BABYLON.serialize(),
  46446. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46447. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  46448. __decorate([
  46449. BABYLON.serialize(),
  46450. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46451. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  46452. __decorate([
  46453. BABYLON.serialize(),
  46454. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46455. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  46456. __decorate([
  46457. BABYLON.serialize(),
  46458. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46459. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  46460. __decorate([
  46461. BABYLON.serialize(),
  46462. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46463. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  46464. __decorate([
  46465. BABYLON.serialize(),
  46466. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46467. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  46468. __decorate([
  46469. BABYLON.serialize(),
  46470. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46471. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  46472. __decorate([
  46473. BABYLON.serialize(),
  46474. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46475. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  46476. __decorate([
  46477. BABYLON.serialize(),
  46478. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46479. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  46480. __decorate([
  46481. BABYLON.serialize(),
  46482. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46483. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  46484. __decorate([
  46485. BABYLON.serialize(),
  46486. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46487. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  46488. __decorate([
  46489. BABYLON.serialize(),
  46490. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46491. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  46492. __decorate([
  46493. BABYLON.serialize(),
  46494. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46495. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  46496. __decorate([
  46497. BABYLON.serialize(),
  46498. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46499. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  46500. __decorate([
  46501. BABYLON.serialize(),
  46502. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46503. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  46504. __decorate([
  46505. BABYLON.serialize(),
  46506. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46507. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  46508. __decorate([
  46509. BABYLON.serialize(),
  46510. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46511. ], PBRMaterial.prototype, "useParallax", void 0);
  46512. __decorate([
  46513. BABYLON.serialize(),
  46514. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46515. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  46516. __decorate([
  46517. BABYLON.serialize(),
  46518. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46519. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  46520. __decorate([
  46521. BABYLON.serialize(),
  46522. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46523. ], PBRMaterial.prototype, "disableLighting", void 0);
  46524. __decorate([
  46525. BABYLON.serialize(),
  46526. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46527. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  46528. __decorate([
  46529. BABYLON.serialize(),
  46530. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46531. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  46532. __decorate([
  46533. BABYLON.serialize(),
  46534. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46535. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  46536. __decorate([
  46537. BABYLON.serialize(),
  46538. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46539. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  46540. __decorate([
  46541. BABYLON.serialize(),
  46542. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46543. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  46544. __decorate([
  46545. BABYLON.serialize(),
  46546. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46547. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  46548. __decorate([
  46549. BABYLON.serialize(),
  46550. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46551. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  46552. __decorate([
  46553. BABYLON.serializeAsTexture(),
  46554. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46555. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  46556. __decorate([
  46557. BABYLON.serialize(),
  46558. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46559. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  46560. __decorate([
  46561. BABYLON.serialize(),
  46562. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46563. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  46564. __decorate([
  46565. BABYLON.serialize(),
  46566. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46567. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  46568. __decorate([
  46569. BABYLON.serialize(),
  46570. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46571. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  46572. __decorate([
  46573. BABYLON.serialize(),
  46574. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46575. ], PBRMaterial.prototype, "unlit", void 0);
  46576. return PBRMaterial;
  46577. }(BABYLON.PBRBaseMaterial));
  46578. BABYLON.PBRMaterial = PBRMaterial;
  46579. })(BABYLON || (BABYLON = {}));
  46580. //# sourceMappingURL=babylon.pbrMaterial.js.map
  46581. var BABYLON;
  46582. (function (BABYLON) {
  46583. /**
  46584. * The PBR material of BJS following the metal roughness convention.
  46585. *
  46586. * This fits to the PBR convention in the GLTF definition:
  46587. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  46588. */
  46589. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  46590. __extends(PBRMetallicRoughnessMaterial, _super);
  46591. /**
  46592. * Instantiates a new PBRMetalRoughnessMaterial instance.
  46593. *
  46594. * @param name The material name
  46595. * @param scene The scene the material will be use in.
  46596. */
  46597. function PBRMetallicRoughnessMaterial(name, scene) {
  46598. var _this = _super.call(this, name, scene) || this;
  46599. _this._useRoughnessFromMetallicTextureAlpha = false;
  46600. _this._useRoughnessFromMetallicTextureGreen = true;
  46601. _this._useMetallnessFromMetallicTextureBlue = true;
  46602. _this.metallic = 1.0;
  46603. _this.roughness = 1.0;
  46604. return _this;
  46605. }
  46606. /**
  46607. * Return the currrent class name of the material.
  46608. */
  46609. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  46610. return "PBRMetallicRoughnessMaterial";
  46611. };
  46612. /**
  46613. * Return the active textures of the material.
  46614. */
  46615. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  46616. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46617. if (this.baseTexture) {
  46618. activeTextures.push(this.baseTexture);
  46619. }
  46620. if (this.metallicRoughnessTexture) {
  46621. activeTextures.push(this.metallicRoughnessTexture);
  46622. }
  46623. return activeTextures;
  46624. };
  46625. /**
  46626. * Checks to see if a texture is used in the material.
  46627. * @param texture - Base texture to use.
  46628. * @returns - Boolean specifying if a texture is used in the material.
  46629. */
  46630. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  46631. if (_super.prototype.hasTexture.call(this, texture)) {
  46632. return true;
  46633. }
  46634. if (this.baseTexture === texture) {
  46635. return true;
  46636. }
  46637. if (this.metallicRoughnessTexture === texture) {
  46638. return true;
  46639. }
  46640. return false;
  46641. };
  46642. /**
  46643. * Makes a duplicate of the current material.
  46644. * @param name - name to use for the new material.
  46645. */
  46646. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  46647. var _this = this;
  46648. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  46649. clone.id = name;
  46650. clone.name = name;
  46651. return clone;
  46652. };
  46653. /**
  46654. * Serialize the material to a parsable JSON object.
  46655. */
  46656. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  46657. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46658. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  46659. return serializationObject;
  46660. };
  46661. /**
  46662. * Parses a JSON object correponding to the serialize function.
  46663. */
  46664. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  46665. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  46666. };
  46667. __decorate([
  46668. BABYLON.serializeAsColor3(),
  46669. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46670. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  46671. __decorate([
  46672. BABYLON.serializeAsTexture(),
  46673. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46674. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  46675. __decorate([
  46676. BABYLON.serialize(),
  46677. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46678. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  46679. __decorate([
  46680. BABYLON.serialize(),
  46681. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46682. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  46683. __decorate([
  46684. BABYLON.serializeAsTexture(),
  46685. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  46686. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  46687. return PBRMetallicRoughnessMaterial;
  46688. }(BABYLON.PBRBaseSimpleMaterial));
  46689. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  46690. })(BABYLON || (BABYLON = {}));
  46691. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  46692. var BABYLON;
  46693. (function (BABYLON) {
  46694. /**
  46695. * The PBR material of BJS following the specular glossiness convention.
  46696. *
  46697. * This fits to the PBR convention in the GLTF definition:
  46698. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  46699. */
  46700. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  46701. __extends(PBRSpecularGlossinessMaterial, _super);
  46702. /**
  46703. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  46704. *
  46705. * @param name The material name
  46706. * @param scene The scene the material will be use in.
  46707. */
  46708. function PBRSpecularGlossinessMaterial(name, scene) {
  46709. var _this = _super.call(this, name, scene) || this;
  46710. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  46711. return _this;
  46712. }
  46713. /**
  46714. * Return the currrent class name of the material.
  46715. */
  46716. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  46717. return "PBRSpecularGlossinessMaterial";
  46718. };
  46719. /**
  46720. * Return the active textures of the material.
  46721. */
  46722. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  46723. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46724. if (this.diffuseTexture) {
  46725. activeTextures.push(this.diffuseTexture);
  46726. }
  46727. if (this.specularGlossinessTexture) {
  46728. activeTextures.push(this.specularGlossinessTexture);
  46729. }
  46730. return activeTextures;
  46731. };
  46732. /**
  46733. * Checks to see if a texture is used in the material.
  46734. * @param texture - Base texture to use.
  46735. * @returns - Boolean specifying if a texture is used in the material.
  46736. */
  46737. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  46738. if (_super.prototype.hasTexture.call(this, texture)) {
  46739. return true;
  46740. }
  46741. if (this.diffuseTexture === texture) {
  46742. return true;
  46743. }
  46744. if (this.specularGlossinessTexture === texture) {
  46745. return true;
  46746. }
  46747. return false;
  46748. };
  46749. /**
  46750. * Makes a duplicate of the current material.
  46751. * @param name - name to use for the new material.
  46752. */
  46753. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  46754. var _this = this;
  46755. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  46756. clone.id = name;
  46757. clone.name = name;
  46758. return clone;
  46759. };
  46760. /**
  46761. * Serialize the material to a parsable JSON object.
  46762. */
  46763. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  46764. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46765. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  46766. return serializationObject;
  46767. };
  46768. /**
  46769. * Parses a JSON object correponding to the serialize function.
  46770. */
  46771. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  46772. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  46773. };
  46774. __decorate([
  46775. BABYLON.serializeAsColor3("diffuse"),
  46776. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46777. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  46778. __decorate([
  46779. BABYLON.serializeAsTexture(),
  46780. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46781. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  46782. __decorate([
  46783. BABYLON.serializeAsColor3("specular"),
  46784. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  46785. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  46786. __decorate([
  46787. BABYLON.serialize(),
  46788. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  46789. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  46790. __decorate([
  46791. BABYLON.serializeAsTexture(),
  46792. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  46793. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  46794. return PBRSpecularGlossinessMaterial;
  46795. }(BABYLON.PBRBaseSimpleMaterial));
  46796. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  46797. })(BABYLON || (BABYLON = {}));
  46798. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  46799. var BABYLON;
  46800. (function (BABYLON) {
  46801. BABYLON.CameraInputTypes = {};
  46802. var CameraInputsManager = /** @class */ (function () {
  46803. function CameraInputsManager(camera) {
  46804. this.attached = {};
  46805. this.camera = camera;
  46806. this.checkInputs = function () { };
  46807. }
  46808. /**
  46809. * Add an input method to a camera.
  46810. * builtin inputs example: camera.inputs.addGamepad();
  46811. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  46812. * @param input camera input method
  46813. */
  46814. CameraInputsManager.prototype.add = function (input) {
  46815. var type = input.getSimpleName();
  46816. if (this.attached[type]) {
  46817. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  46818. return;
  46819. }
  46820. this.attached[type] = input;
  46821. input.camera = this.camera;
  46822. //for checkInputs, we are dynamically creating a function
  46823. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  46824. if (input.checkInputs) {
  46825. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46826. }
  46827. if (this.attachedElement) {
  46828. input.attachControl(this.attachedElement);
  46829. }
  46830. };
  46831. /**
  46832. * Remove a specific input method from a camera
  46833. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  46834. * @param inputToRemove camera input method
  46835. */
  46836. CameraInputsManager.prototype.remove = function (inputToRemove) {
  46837. for (var cam in this.attached) {
  46838. var input = this.attached[cam];
  46839. if (input === inputToRemove) {
  46840. input.detachControl(this.attachedElement);
  46841. input.camera = null;
  46842. delete this.attached[cam];
  46843. this.rebuildInputCheck();
  46844. }
  46845. }
  46846. };
  46847. CameraInputsManager.prototype.removeByType = function (inputType) {
  46848. for (var cam in this.attached) {
  46849. var input = this.attached[cam];
  46850. if (input.getClassName() === inputType) {
  46851. input.detachControl(this.attachedElement);
  46852. input.camera = null;
  46853. delete this.attached[cam];
  46854. this.rebuildInputCheck();
  46855. }
  46856. }
  46857. };
  46858. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  46859. var current = this.checkInputs;
  46860. return function () {
  46861. current();
  46862. fn();
  46863. };
  46864. };
  46865. CameraInputsManager.prototype.attachInput = function (input) {
  46866. if (this.attachedElement) {
  46867. input.attachControl(this.attachedElement, this.noPreventDefault);
  46868. }
  46869. };
  46870. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  46871. if (noPreventDefault === void 0) { noPreventDefault = false; }
  46872. if (this.attachedElement) {
  46873. return;
  46874. }
  46875. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  46876. this.attachedElement = element;
  46877. this.noPreventDefault = noPreventDefault;
  46878. for (var cam in this.attached) {
  46879. this.attached[cam].attachControl(element, noPreventDefault);
  46880. }
  46881. };
  46882. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  46883. if (disconnect === void 0) { disconnect = false; }
  46884. if (this.attachedElement !== element) {
  46885. return;
  46886. }
  46887. for (var cam in this.attached) {
  46888. this.attached[cam].detachControl(element);
  46889. if (disconnect) {
  46890. this.attached[cam].camera = null;
  46891. }
  46892. }
  46893. this.attachedElement = null;
  46894. };
  46895. CameraInputsManager.prototype.rebuildInputCheck = function () {
  46896. this.checkInputs = function () { };
  46897. for (var cam in this.attached) {
  46898. var input = this.attached[cam];
  46899. if (input.checkInputs) {
  46900. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46901. }
  46902. }
  46903. };
  46904. /**
  46905. * Remove all attached input methods from a camera
  46906. */
  46907. CameraInputsManager.prototype.clear = function () {
  46908. if (this.attachedElement) {
  46909. this.detachElement(this.attachedElement, true);
  46910. }
  46911. this.attached = {};
  46912. this.attachedElement = null;
  46913. this.checkInputs = function () { };
  46914. };
  46915. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  46916. var inputs = {};
  46917. for (var cam in this.attached) {
  46918. var input = this.attached[cam];
  46919. var res = BABYLON.SerializationHelper.Serialize(input);
  46920. inputs[input.getClassName()] = res;
  46921. }
  46922. serializedCamera.inputsmgr = inputs;
  46923. };
  46924. CameraInputsManager.prototype.parse = function (parsedCamera) {
  46925. var parsedInputs = parsedCamera.inputsmgr;
  46926. if (parsedInputs) {
  46927. this.clear();
  46928. for (var n in parsedInputs) {
  46929. var construct = BABYLON.CameraInputTypes[n];
  46930. if (construct) {
  46931. var parsedinput = parsedInputs[n];
  46932. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  46933. this.add(input);
  46934. }
  46935. }
  46936. }
  46937. else {
  46938. //2016-03-08 this part is for managing backward compatibility
  46939. for (var n in this.attached) {
  46940. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  46941. if (construct) {
  46942. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  46943. this.remove(this.attached[n]);
  46944. this.add(input);
  46945. }
  46946. }
  46947. }
  46948. };
  46949. return CameraInputsManager;
  46950. }());
  46951. BABYLON.CameraInputsManager = CameraInputsManager;
  46952. })(BABYLON || (BABYLON = {}));
  46953. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  46954. var BABYLON;
  46955. (function (BABYLON) {
  46956. var TargetCamera = /** @class */ (function (_super) {
  46957. __extends(TargetCamera, _super);
  46958. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46959. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46960. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46961. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46962. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  46963. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  46964. _this.speed = 2.0;
  46965. _this.noRotationConstraint = false;
  46966. _this.lockedTarget = null;
  46967. _this._currentTarget = BABYLON.Vector3.Zero();
  46968. _this._viewMatrix = BABYLON.Matrix.Zero();
  46969. _this._camMatrix = BABYLON.Matrix.Zero();
  46970. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  46971. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  46972. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  46973. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  46974. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  46975. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  46976. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  46977. return _this;
  46978. }
  46979. TargetCamera.prototype.getFrontPosition = function (distance) {
  46980. this.getWorldMatrix();
  46981. var direction = this.getTarget().subtract(this.position);
  46982. direction.normalize();
  46983. direction.scaleInPlace(distance);
  46984. return this.globalPosition.add(direction);
  46985. };
  46986. TargetCamera.prototype._getLockedTargetPosition = function () {
  46987. if (!this.lockedTarget) {
  46988. return null;
  46989. }
  46990. if (this.lockedTarget.absolutePosition) {
  46991. this.lockedTarget.computeWorldMatrix();
  46992. }
  46993. return this.lockedTarget.absolutePosition || this.lockedTarget;
  46994. };
  46995. TargetCamera.prototype.storeState = function () {
  46996. this._storedPosition = this.position.clone();
  46997. this._storedRotation = this.rotation.clone();
  46998. if (this.rotationQuaternion) {
  46999. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  47000. }
  47001. return _super.prototype.storeState.call(this);
  47002. };
  47003. /**
  47004. * Restored camera state. You must call storeState() first
  47005. */
  47006. TargetCamera.prototype._restoreStateValues = function () {
  47007. if (!_super.prototype._restoreStateValues.call(this)) {
  47008. return false;
  47009. }
  47010. this.position = this._storedPosition.clone();
  47011. this.rotation = this._storedRotation.clone();
  47012. if (this.rotationQuaternion) {
  47013. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  47014. }
  47015. this.cameraDirection.copyFromFloats(0, 0, 0);
  47016. this.cameraRotation.copyFromFloats(0, 0);
  47017. return true;
  47018. };
  47019. // Cache
  47020. TargetCamera.prototype._initCache = function () {
  47021. _super.prototype._initCache.call(this);
  47022. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47023. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47024. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47025. };
  47026. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  47027. if (!ignoreParentClass) {
  47028. _super.prototype._updateCache.call(this);
  47029. }
  47030. var lockedTargetPosition = this._getLockedTargetPosition();
  47031. if (!lockedTargetPosition) {
  47032. this._cache.lockedTarget = null;
  47033. }
  47034. else {
  47035. if (!this._cache.lockedTarget) {
  47036. this._cache.lockedTarget = lockedTargetPosition.clone();
  47037. }
  47038. else {
  47039. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  47040. }
  47041. }
  47042. this._cache.rotation.copyFrom(this.rotation);
  47043. if (this.rotationQuaternion)
  47044. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47045. };
  47046. // Synchronized
  47047. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  47048. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  47049. return false;
  47050. }
  47051. var lockedTargetPosition = this._getLockedTargetPosition();
  47052. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  47053. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  47054. };
  47055. // Methods
  47056. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  47057. var engine = this.getEngine();
  47058. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  47059. };
  47060. // Target
  47061. TargetCamera.prototype.setTarget = function (target) {
  47062. this.upVector.normalize();
  47063. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  47064. this._camMatrix.invert();
  47065. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  47066. var vDir = target.subtract(this.position);
  47067. if (vDir.x >= 0.0) {
  47068. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  47069. }
  47070. else {
  47071. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  47072. }
  47073. this.rotation.z = 0;
  47074. if (isNaN(this.rotation.x)) {
  47075. this.rotation.x = 0;
  47076. }
  47077. if (isNaN(this.rotation.y)) {
  47078. this.rotation.y = 0;
  47079. }
  47080. if (isNaN(this.rotation.z)) {
  47081. this.rotation.z = 0;
  47082. }
  47083. if (this.rotationQuaternion) {
  47084. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  47085. }
  47086. };
  47087. /**
  47088. * Return the current target position of the camera. This value is expressed in local space.
  47089. */
  47090. TargetCamera.prototype.getTarget = function () {
  47091. return this._currentTarget;
  47092. };
  47093. TargetCamera.prototype._decideIfNeedsToMove = function () {
  47094. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  47095. };
  47096. TargetCamera.prototype._updatePosition = function () {
  47097. if (this.parent) {
  47098. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  47099. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  47100. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  47101. return;
  47102. }
  47103. this.position.addInPlace(this.cameraDirection);
  47104. };
  47105. TargetCamera.prototype._checkInputs = function () {
  47106. var needToMove = this._decideIfNeedsToMove();
  47107. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  47108. // Move
  47109. if (needToMove) {
  47110. this._updatePosition();
  47111. }
  47112. // Rotate
  47113. if (needToRotate) {
  47114. this.rotation.x += this.cameraRotation.x;
  47115. this.rotation.y += this.cameraRotation.y;
  47116. //rotate, if quaternion is set and rotation was used
  47117. if (this.rotationQuaternion) {
  47118. var len = this.rotation.lengthSquared();
  47119. if (len) {
  47120. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  47121. }
  47122. }
  47123. if (!this.noRotationConstraint) {
  47124. var limit = (Math.PI / 2) * 0.95;
  47125. if (this.rotation.x > limit)
  47126. this.rotation.x = limit;
  47127. if (this.rotation.x < -limit)
  47128. this.rotation.x = -limit;
  47129. }
  47130. }
  47131. // Inertia
  47132. if (needToMove) {
  47133. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  47134. this.cameraDirection.x = 0;
  47135. }
  47136. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  47137. this.cameraDirection.y = 0;
  47138. }
  47139. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  47140. this.cameraDirection.z = 0;
  47141. }
  47142. this.cameraDirection.scaleInPlace(this.inertia);
  47143. }
  47144. if (needToRotate) {
  47145. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  47146. this.cameraRotation.x = 0;
  47147. }
  47148. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  47149. this.cameraRotation.y = 0;
  47150. }
  47151. this.cameraRotation.scaleInPlace(this.inertia);
  47152. }
  47153. _super.prototype._checkInputs.call(this);
  47154. };
  47155. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  47156. if (this.rotationQuaternion) {
  47157. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  47158. }
  47159. else {
  47160. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  47161. }
  47162. //update the up vector!
  47163. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  47164. };
  47165. TargetCamera.prototype._getViewMatrix = function () {
  47166. if (this.lockedTarget) {
  47167. this.setTarget(this._getLockedTargetPosition());
  47168. }
  47169. // Compute
  47170. this._updateCameraRotationMatrix();
  47171. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  47172. // Computing target and final matrix
  47173. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  47174. this._computeViewMatrix(this.position, this._currentTarget, this._currentUpVector);
  47175. return this._viewMatrix;
  47176. };
  47177. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  47178. if (this.parent) {
  47179. var parentWorldMatrix = this.parent.getWorldMatrix();
  47180. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._globalPosition);
  47181. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  47182. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  47183. this._markSyncedWithParent();
  47184. }
  47185. else {
  47186. this._globalPosition.copyFrom(this.position);
  47187. this._globalCurrentTarget.copyFrom(target);
  47188. this._globalCurrentUpVector.copyFrom(up);
  47189. }
  47190. if (this.getScene().useRightHandedSystem) {
  47191. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  47192. }
  47193. else {
  47194. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  47195. }
  47196. };
  47197. /**
  47198. * @override
  47199. * Override Camera.createRigCamera
  47200. */
  47201. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  47202. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  47203. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  47204. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  47205. if (!this.rotationQuaternion) {
  47206. this.rotationQuaternion = new BABYLON.Quaternion();
  47207. }
  47208. rigCamera._cameraRigParams = {};
  47209. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  47210. }
  47211. return rigCamera;
  47212. }
  47213. return null;
  47214. };
  47215. /**
  47216. * @override
  47217. * Override Camera._updateRigCameras
  47218. */
  47219. TargetCamera.prototype._updateRigCameras = function () {
  47220. var camLeft = this._rigCameras[0];
  47221. var camRight = this._rigCameras[1];
  47222. switch (this.cameraRigMode) {
  47223. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  47224. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  47225. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  47226. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  47227. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  47228. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  47229. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  47230. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  47231. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  47232. camLeft.setTarget(this.getTarget());
  47233. camRight.setTarget(this.getTarget());
  47234. break;
  47235. case BABYLON.Camera.RIG_MODE_VR:
  47236. if (camLeft.rotationQuaternion) {
  47237. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47238. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47239. }
  47240. else {
  47241. camLeft.rotation.copyFrom(this.rotation);
  47242. camRight.rotation.copyFrom(this.rotation);
  47243. }
  47244. camLeft.position.copyFrom(this.position);
  47245. camRight.position.copyFrom(this.position);
  47246. break;
  47247. }
  47248. _super.prototype._updateRigCameras.call(this);
  47249. };
  47250. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  47251. if (!this._rigCamTransformMatrix) {
  47252. this._rigCamTransformMatrix = new BABYLON.Matrix();
  47253. }
  47254. var target = this.getTarget();
  47255. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  47256. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  47257. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  47258. };
  47259. TargetCamera.prototype.getClassName = function () {
  47260. return "TargetCamera";
  47261. };
  47262. __decorate([
  47263. BABYLON.serializeAsVector3()
  47264. ], TargetCamera.prototype, "rotation", void 0);
  47265. __decorate([
  47266. BABYLON.serialize()
  47267. ], TargetCamera.prototype, "speed", void 0);
  47268. __decorate([
  47269. BABYLON.serializeAsMeshReference("lockedTargetId")
  47270. ], TargetCamera.prototype, "lockedTarget", void 0);
  47271. return TargetCamera;
  47272. }(BABYLON.Camera));
  47273. BABYLON.TargetCamera = TargetCamera;
  47274. })(BABYLON || (BABYLON = {}));
  47275. //# sourceMappingURL=babylon.targetCamera.js.map
  47276. var BABYLON;
  47277. (function (BABYLON) {
  47278. var FreeCameraMouseInput = /** @class */ (function () {
  47279. function FreeCameraMouseInput(touchEnabled) {
  47280. if (touchEnabled === void 0) { touchEnabled = true; }
  47281. this.touchEnabled = touchEnabled;
  47282. this.buttons = [0, 1, 2];
  47283. this.angularSensibility = 2000.0;
  47284. this.previousPosition = null;
  47285. }
  47286. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  47287. var _this = this;
  47288. var engine = this.camera.getEngine();
  47289. if (!this._pointerInput) {
  47290. this._pointerInput = function (p, s) {
  47291. var evt = p.event;
  47292. if (engine.isInVRExclusivePointerMode) {
  47293. return;
  47294. }
  47295. if (!_this.touchEnabled && evt.pointerType === "touch") {
  47296. return;
  47297. }
  47298. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47299. return;
  47300. }
  47301. var srcElement = (evt.srcElement || evt.target);
  47302. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47303. try {
  47304. srcElement.setPointerCapture(evt.pointerId);
  47305. }
  47306. catch (e) {
  47307. //Nothing to do with the error. Execution will continue.
  47308. }
  47309. _this.previousPosition = {
  47310. x: evt.clientX,
  47311. y: evt.clientY
  47312. };
  47313. if (!noPreventDefault) {
  47314. evt.preventDefault();
  47315. element.focus();
  47316. }
  47317. }
  47318. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47319. try {
  47320. srcElement.releasePointerCapture(evt.pointerId);
  47321. }
  47322. catch (e) {
  47323. //Nothing to do with the error.
  47324. }
  47325. _this.previousPosition = null;
  47326. if (!noPreventDefault) {
  47327. evt.preventDefault();
  47328. }
  47329. }
  47330. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47331. if (!_this.previousPosition || engine.isPointerLock) {
  47332. return;
  47333. }
  47334. var offsetX = evt.clientX - _this.previousPosition.x;
  47335. if (_this.camera.getScene().useRightHandedSystem)
  47336. offsetX *= -1;
  47337. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  47338. offsetX *= -1;
  47339. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  47340. var offsetY = evt.clientY - _this.previousPosition.y;
  47341. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  47342. _this.previousPosition = {
  47343. x: evt.clientX,
  47344. y: evt.clientY
  47345. };
  47346. if (!noPreventDefault) {
  47347. evt.preventDefault();
  47348. }
  47349. }
  47350. };
  47351. }
  47352. this._onMouseMove = function (evt) {
  47353. if (!engine.isPointerLock) {
  47354. return;
  47355. }
  47356. if (engine.isInVRExclusivePointerMode) {
  47357. return;
  47358. }
  47359. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47360. if (_this.camera.getScene().useRightHandedSystem)
  47361. offsetX *= -1;
  47362. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  47363. offsetX *= -1;
  47364. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  47365. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47366. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  47367. _this.previousPosition = null;
  47368. if (!noPreventDefault) {
  47369. evt.preventDefault();
  47370. }
  47371. };
  47372. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  47373. element.addEventListener("mousemove", this._onMouseMove, false);
  47374. };
  47375. FreeCameraMouseInput.prototype.detachControl = function (element) {
  47376. if (this._observer && element) {
  47377. this.camera.getScene().onPointerObservable.remove(this._observer);
  47378. if (this._onMouseMove) {
  47379. element.removeEventListener("mousemove", this._onMouseMove);
  47380. }
  47381. this._observer = null;
  47382. this._onMouseMove = null;
  47383. this.previousPosition = null;
  47384. }
  47385. };
  47386. FreeCameraMouseInput.prototype.getClassName = function () {
  47387. return "FreeCameraMouseInput";
  47388. };
  47389. FreeCameraMouseInput.prototype.getSimpleName = function () {
  47390. return "mouse";
  47391. };
  47392. __decorate([
  47393. BABYLON.serialize()
  47394. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  47395. __decorate([
  47396. BABYLON.serialize()
  47397. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  47398. return FreeCameraMouseInput;
  47399. }());
  47400. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  47401. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  47402. })(BABYLON || (BABYLON = {}));
  47403. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  47404. var BABYLON;
  47405. (function (BABYLON) {
  47406. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  47407. function FreeCameraKeyboardMoveInput() {
  47408. this._keys = new Array();
  47409. this.keysUp = [38];
  47410. this.keysDown = [40];
  47411. this.keysLeft = [37];
  47412. this.keysRight = [39];
  47413. }
  47414. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47415. var _this = this;
  47416. if (this._onCanvasBlurObserver) {
  47417. return;
  47418. }
  47419. this._scene = this.camera.getScene();
  47420. this._engine = this._scene.getEngine();
  47421. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47422. _this._keys = [];
  47423. });
  47424. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47425. var evt = info.event;
  47426. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47427. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47428. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47429. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47430. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47431. var index = _this._keys.indexOf(evt.keyCode);
  47432. if (index === -1) {
  47433. _this._keys.push(evt.keyCode);
  47434. }
  47435. if (!noPreventDefault) {
  47436. evt.preventDefault();
  47437. }
  47438. }
  47439. }
  47440. else {
  47441. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47442. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47443. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47444. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47445. var index = _this._keys.indexOf(evt.keyCode);
  47446. if (index >= 0) {
  47447. _this._keys.splice(index, 1);
  47448. }
  47449. if (!noPreventDefault) {
  47450. evt.preventDefault();
  47451. }
  47452. }
  47453. }
  47454. });
  47455. };
  47456. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47457. if (this._scene) {
  47458. if (this._onKeyboardObserver) {
  47459. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47460. }
  47461. if (this._onCanvasBlurObserver) {
  47462. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47463. }
  47464. this._onKeyboardObserver = null;
  47465. this._onCanvasBlurObserver = null;
  47466. }
  47467. this._keys = [];
  47468. };
  47469. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47470. if (this._onKeyboardObserver) {
  47471. var camera = this.camera;
  47472. // Keyboard
  47473. for (var index = 0; index < this._keys.length; index++) {
  47474. var keyCode = this._keys[index];
  47475. var speed = camera._computeLocalCameraSpeed();
  47476. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47477. camera._localDirection.copyFromFloats(-speed, 0, 0);
  47478. }
  47479. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47480. camera._localDirection.copyFromFloats(0, 0, speed);
  47481. }
  47482. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47483. camera._localDirection.copyFromFloats(speed, 0, 0);
  47484. }
  47485. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47486. camera._localDirection.copyFromFloats(0, 0, -speed);
  47487. }
  47488. if (camera.getScene().useRightHandedSystem) {
  47489. camera._localDirection.z *= -1;
  47490. }
  47491. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  47492. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  47493. camera.cameraDirection.addInPlace(camera._transformedDirection);
  47494. }
  47495. }
  47496. };
  47497. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  47498. return "FreeCameraKeyboardMoveInput";
  47499. };
  47500. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  47501. this._keys = [];
  47502. };
  47503. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47504. return "keyboard";
  47505. };
  47506. __decorate([
  47507. BABYLON.serialize()
  47508. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47509. __decorate([
  47510. BABYLON.serialize()
  47511. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47512. __decorate([
  47513. BABYLON.serialize()
  47514. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47515. __decorate([
  47516. BABYLON.serialize()
  47517. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47518. return FreeCameraKeyboardMoveInput;
  47519. }());
  47520. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  47521. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  47522. })(BABYLON || (BABYLON = {}));
  47523. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  47524. var BABYLON;
  47525. (function (BABYLON) {
  47526. var FreeCameraInputsManager = /** @class */ (function (_super) {
  47527. __extends(FreeCameraInputsManager, _super);
  47528. function FreeCameraInputsManager(camera) {
  47529. return _super.call(this, camera) || this;
  47530. }
  47531. FreeCameraInputsManager.prototype.addKeyboard = function () {
  47532. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  47533. return this;
  47534. };
  47535. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  47536. if (touchEnabled === void 0) { touchEnabled = true; }
  47537. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  47538. return this;
  47539. };
  47540. FreeCameraInputsManager.prototype.addGamepad = function () {
  47541. this.add(new BABYLON.FreeCameraGamepadInput());
  47542. return this;
  47543. };
  47544. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  47545. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  47546. return this;
  47547. };
  47548. FreeCameraInputsManager.prototype.addTouch = function () {
  47549. this.add(new BABYLON.FreeCameraTouchInput());
  47550. return this;
  47551. };
  47552. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  47553. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  47554. return this;
  47555. };
  47556. return FreeCameraInputsManager;
  47557. }(BABYLON.CameraInputsManager));
  47558. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  47559. })(BABYLON || (BABYLON = {}));
  47560. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  47561. var BABYLON;
  47562. (function (BABYLON) {
  47563. var FreeCamera = /** @class */ (function (_super) {
  47564. __extends(FreeCamera, _super);
  47565. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  47566. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47567. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  47568. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  47569. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  47570. _this.checkCollisions = false;
  47571. _this.applyGravity = false;
  47572. _this._needMoveForGravity = false;
  47573. _this._oldPosition = BABYLON.Vector3.Zero();
  47574. _this._diffPosition = BABYLON.Vector3.Zero();
  47575. _this._newPosition = BABYLON.Vector3.Zero();
  47576. // Collisions
  47577. _this._collisionMask = -1;
  47578. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47579. if (collidedMesh === void 0) { collidedMesh = null; }
  47580. //TODO move this to the collision coordinator!
  47581. if (_this.getScene().workerCollisions)
  47582. newPosition.multiplyInPlace(_this._collider._radius);
  47583. var updatePosition = function (newPos) {
  47584. _this._newPosition.copyFrom(newPos);
  47585. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  47586. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  47587. _this.position.addInPlace(_this._diffPosition);
  47588. if (_this.onCollide && collidedMesh) {
  47589. _this.onCollide(collidedMesh);
  47590. }
  47591. }
  47592. };
  47593. updatePosition(newPosition);
  47594. };
  47595. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  47596. _this.inputs.addKeyboard().addMouse();
  47597. return _this;
  47598. }
  47599. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  47600. //-- begin properties for backward compatibility for inputs
  47601. /**
  47602. * Gets the input sensibility for a mouse input. (default is 2000.0)
  47603. * Higher values reduce sensitivity.
  47604. */
  47605. get: function () {
  47606. var mouse = this.inputs.attached["mouse"];
  47607. if (mouse)
  47608. return mouse.angularSensibility;
  47609. return 0;
  47610. },
  47611. /**
  47612. * Sets the input sensibility for a mouse input. (default is 2000.0)
  47613. * Higher values reduce sensitivity.
  47614. */
  47615. set: function (value) {
  47616. var mouse = this.inputs.attached["mouse"];
  47617. if (mouse)
  47618. mouse.angularSensibility = value;
  47619. },
  47620. enumerable: true,
  47621. configurable: true
  47622. });
  47623. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  47624. get: function () {
  47625. var keyboard = this.inputs.attached["keyboard"];
  47626. if (keyboard)
  47627. return keyboard.keysUp;
  47628. return [];
  47629. },
  47630. set: function (value) {
  47631. var keyboard = this.inputs.attached["keyboard"];
  47632. if (keyboard)
  47633. keyboard.keysUp = value;
  47634. },
  47635. enumerable: true,
  47636. configurable: true
  47637. });
  47638. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  47639. get: function () {
  47640. var keyboard = this.inputs.attached["keyboard"];
  47641. if (keyboard)
  47642. return keyboard.keysDown;
  47643. return [];
  47644. },
  47645. set: function (value) {
  47646. var keyboard = this.inputs.attached["keyboard"];
  47647. if (keyboard)
  47648. keyboard.keysDown = value;
  47649. },
  47650. enumerable: true,
  47651. configurable: true
  47652. });
  47653. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  47654. get: function () {
  47655. var keyboard = this.inputs.attached["keyboard"];
  47656. if (keyboard)
  47657. return keyboard.keysLeft;
  47658. return [];
  47659. },
  47660. set: function (value) {
  47661. var keyboard = this.inputs.attached["keyboard"];
  47662. if (keyboard)
  47663. keyboard.keysLeft = value;
  47664. },
  47665. enumerable: true,
  47666. configurable: true
  47667. });
  47668. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  47669. get: function () {
  47670. var keyboard = this.inputs.attached["keyboard"];
  47671. if (keyboard)
  47672. return keyboard.keysRight;
  47673. return [];
  47674. },
  47675. set: function (value) {
  47676. var keyboard = this.inputs.attached["keyboard"];
  47677. if (keyboard)
  47678. keyboard.keysRight = value;
  47679. },
  47680. enumerable: true,
  47681. configurable: true
  47682. });
  47683. // Controls
  47684. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  47685. this.inputs.attachElement(element, noPreventDefault);
  47686. };
  47687. FreeCamera.prototype.detachControl = function (element) {
  47688. this.inputs.detachElement(element);
  47689. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  47690. this.cameraRotation = new BABYLON.Vector2(0, 0);
  47691. };
  47692. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  47693. get: function () {
  47694. return this._collisionMask;
  47695. },
  47696. set: function (mask) {
  47697. this._collisionMask = !isNaN(mask) ? mask : -1;
  47698. },
  47699. enumerable: true,
  47700. configurable: true
  47701. });
  47702. FreeCamera.prototype._collideWithWorld = function (displacement) {
  47703. var globalPosition;
  47704. if (this.parent) {
  47705. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  47706. }
  47707. else {
  47708. globalPosition = this.position;
  47709. }
  47710. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  47711. this._oldPosition.addInPlace(this.ellipsoidOffset);
  47712. if (!this._collider) {
  47713. this._collider = new BABYLON.Collider();
  47714. }
  47715. this._collider._radius = this.ellipsoid;
  47716. this._collider.collisionMask = this._collisionMask;
  47717. //no need for clone, as long as gravity is not on.
  47718. var actualDisplacement = displacement;
  47719. //add gravity to the direction to prevent the dual-collision checking
  47720. if (this.applyGravity) {
  47721. //this prevents mending with cameraDirection, a global variable of the free camera class.
  47722. actualDisplacement = displacement.add(this.getScene().gravity);
  47723. }
  47724. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  47725. };
  47726. FreeCamera.prototype._checkInputs = function () {
  47727. if (!this._localDirection) {
  47728. this._localDirection = BABYLON.Vector3.Zero();
  47729. this._transformedDirection = BABYLON.Vector3.Zero();
  47730. }
  47731. this.inputs.checkInputs();
  47732. _super.prototype._checkInputs.call(this);
  47733. };
  47734. FreeCamera.prototype._decideIfNeedsToMove = function () {
  47735. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  47736. };
  47737. FreeCamera.prototype._updatePosition = function () {
  47738. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  47739. this._collideWithWorld(this.cameraDirection);
  47740. }
  47741. else {
  47742. _super.prototype._updatePosition.call(this);
  47743. }
  47744. };
  47745. FreeCamera.prototype.dispose = function () {
  47746. this.inputs.clear();
  47747. _super.prototype.dispose.call(this);
  47748. };
  47749. FreeCamera.prototype.getClassName = function () {
  47750. return "FreeCamera";
  47751. };
  47752. __decorate([
  47753. BABYLON.serializeAsVector3()
  47754. ], FreeCamera.prototype, "ellipsoid", void 0);
  47755. __decorate([
  47756. BABYLON.serializeAsVector3()
  47757. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  47758. __decorate([
  47759. BABYLON.serialize()
  47760. ], FreeCamera.prototype, "checkCollisions", void 0);
  47761. __decorate([
  47762. BABYLON.serialize()
  47763. ], FreeCamera.prototype, "applyGravity", void 0);
  47764. return FreeCamera;
  47765. }(BABYLON.TargetCamera));
  47766. BABYLON.FreeCamera = FreeCamera;
  47767. })(BABYLON || (BABYLON = {}));
  47768. //# sourceMappingURL=babylon.freeCamera.js.map
  47769. var BABYLON;
  47770. (function (BABYLON) {
  47771. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  47772. function ArcRotateCameraKeyboardMoveInput() {
  47773. this._keys = new Array();
  47774. this.keysUp = [38];
  47775. this.keysDown = [40];
  47776. this.keysLeft = [37];
  47777. this.keysRight = [39];
  47778. this.keysReset = [220];
  47779. this.panningSensibility = 50.0;
  47780. this.zoomingSensibility = 25.0;
  47781. this.useAltToZoom = true;
  47782. }
  47783. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47784. var _this = this;
  47785. if (this._onCanvasBlurObserver) {
  47786. return;
  47787. }
  47788. this._scene = this.camera.getScene();
  47789. this._engine = this._scene.getEngine();
  47790. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47791. _this._keys = [];
  47792. });
  47793. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47794. var evt = info.event;
  47795. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47796. _this._ctrlPressed = evt.ctrlKey;
  47797. _this._altPressed = evt.altKey;
  47798. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47799. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47800. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47801. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47802. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47803. var index = _this._keys.indexOf(evt.keyCode);
  47804. if (index === -1) {
  47805. _this._keys.push(evt.keyCode);
  47806. }
  47807. if (evt.preventDefault) {
  47808. if (!noPreventDefault) {
  47809. evt.preventDefault();
  47810. }
  47811. }
  47812. }
  47813. }
  47814. else {
  47815. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47816. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47817. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47818. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47819. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47820. var index = _this._keys.indexOf(evt.keyCode);
  47821. if (index >= 0) {
  47822. _this._keys.splice(index, 1);
  47823. }
  47824. if (evt.preventDefault) {
  47825. if (!noPreventDefault) {
  47826. evt.preventDefault();
  47827. }
  47828. }
  47829. }
  47830. }
  47831. });
  47832. };
  47833. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47834. if (this._scene) {
  47835. if (this._onKeyboardObserver) {
  47836. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47837. }
  47838. if (this._onCanvasBlurObserver) {
  47839. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47840. }
  47841. this._onKeyboardObserver = null;
  47842. this._onCanvasBlurObserver = null;
  47843. }
  47844. this._keys = [];
  47845. };
  47846. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47847. if (this._onKeyboardObserver) {
  47848. var camera = this.camera;
  47849. for (var index = 0; index < this._keys.length; index++) {
  47850. var keyCode = this._keys[index];
  47851. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47852. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47853. camera.inertialPanningX -= 1 / this.panningSensibility;
  47854. }
  47855. else {
  47856. camera.inertialAlphaOffset -= 0.01;
  47857. }
  47858. }
  47859. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47860. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47861. camera.inertialPanningY += 1 / this.panningSensibility;
  47862. }
  47863. else if (this._altPressed && this.useAltToZoom) {
  47864. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  47865. }
  47866. else {
  47867. camera.inertialBetaOffset -= 0.01;
  47868. }
  47869. }
  47870. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47871. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47872. camera.inertialPanningX += 1 / this.panningSensibility;
  47873. }
  47874. else {
  47875. camera.inertialAlphaOffset += 0.01;
  47876. }
  47877. }
  47878. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47879. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47880. camera.inertialPanningY -= 1 / this.panningSensibility;
  47881. }
  47882. else if (this._altPressed && this.useAltToZoom) {
  47883. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  47884. }
  47885. else {
  47886. camera.inertialBetaOffset += 0.01;
  47887. }
  47888. }
  47889. else if (this.keysReset.indexOf(keyCode) !== -1) {
  47890. camera.restoreState();
  47891. }
  47892. }
  47893. }
  47894. };
  47895. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  47896. return "ArcRotateCameraKeyboardMoveInput";
  47897. };
  47898. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47899. return "keyboard";
  47900. };
  47901. __decorate([
  47902. BABYLON.serialize()
  47903. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47904. __decorate([
  47905. BABYLON.serialize()
  47906. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47907. __decorate([
  47908. BABYLON.serialize()
  47909. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47910. __decorate([
  47911. BABYLON.serialize()
  47912. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47913. __decorate([
  47914. BABYLON.serialize()
  47915. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  47916. __decorate([
  47917. BABYLON.serialize()
  47918. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  47919. __decorate([
  47920. BABYLON.serialize()
  47921. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  47922. __decorate([
  47923. BABYLON.serialize()
  47924. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  47925. return ArcRotateCameraKeyboardMoveInput;
  47926. }());
  47927. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  47928. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  47929. })(BABYLON || (BABYLON = {}));
  47930. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  47931. var BABYLON;
  47932. (function (BABYLON) {
  47933. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  47934. function ArcRotateCameraMouseWheelInput() {
  47935. this.wheelPrecision = 3.0;
  47936. /**
  47937. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  47938. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  47939. */
  47940. this.wheelDeltaPercentage = 0;
  47941. }
  47942. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  47943. var _this = this;
  47944. this._wheel = function (p, s) {
  47945. //sanity check - this should be a PointerWheel event.
  47946. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  47947. return;
  47948. var event = p.event;
  47949. var delta = 0;
  47950. if (event.wheelDelta) {
  47951. if (_this.wheelDeltaPercentage) {
  47952. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  47953. if (event.wheelDelta > 0) {
  47954. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  47955. }
  47956. else {
  47957. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  47958. }
  47959. }
  47960. else {
  47961. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  47962. }
  47963. }
  47964. else if (event.detail) {
  47965. delta = -event.detail / _this.wheelPrecision;
  47966. }
  47967. if (delta)
  47968. _this.camera.inertialRadiusOffset += delta;
  47969. if (event.preventDefault) {
  47970. if (!noPreventDefault) {
  47971. event.preventDefault();
  47972. }
  47973. }
  47974. };
  47975. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  47976. };
  47977. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  47978. if (this._observer && element) {
  47979. this.camera.getScene().onPointerObservable.remove(this._observer);
  47980. this._observer = null;
  47981. this._wheel = null;
  47982. }
  47983. };
  47984. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  47985. return "ArcRotateCameraMouseWheelInput";
  47986. };
  47987. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  47988. return "mousewheel";
  47989. };
  47990. __decorate([
  47991. BABYLON.serialize()
  47992. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  47993. __decorate([
  47994. BABYLON.serialize()
  47995. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  47996. return ArcRotateCameraMouseWheelInput;
  47997. }());
  47998. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  47999. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  48000. })(BABYLON || (BABYLON = {}));
  48001. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  48002. var BABYLON;
  48003. (function (BABYLON) {
  48004. var ArcRotateCameraPointersInput = /** @class */ (function () {
  48005. function ArcRotateCameraPointersInput() {
  48006. this.buttons = [0, 1, 2];
  48007. this.angularSensibilityX = 1000.0;
  48008. this.angularSensibilityY = 1000.0;
  48009. this.pinchPrecision = 12.0;
  48010. /**
  48011. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  48012. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  48013. */
  48014. this.pinchDeltaPercentage = 0;
  48015. this.panningSensibility = 1000.0;
  48016. this.multiTouchPanning = true;
  48017. this.multiTouchPanAndZoom = true;
  48018. this._isPanClick = false;
  48019. this.pinchInwards = true;
  48020. }
  48021. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  48022. var _this = this;
  48023. var engine = this.camera.getEngine();
  48024. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  48025. var pointA = null;
  48026. var pointB = null;
  48027. var previousPinchSquaredDistance = 0;
  48028. var initialDistance = 0;
  48029. var twoFingerActivityCount = 0;
  48030. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  48031. this._pointerInput = function (p, s) {
  48032. var evt = p.event;
  48033. var isTouch = p.event.pointerType === "touch";
  48034. if (engine.isInVRExclusivePointerMode) {
  48035. return;
  48036. }
  48037. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  48038. return;
  48039. }
  48040. var srcElement = (evt.srcElement || evt.target);
  48041. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  48042. try {
  48043. srcElement.setPointerCapture(evt.pointerId);
  48044. }
  48045. catch (e) {
  48046. //Nothing to do with the error. Execution will continue.
  48047. }
  48048. // Manage panning with pan button click
  48049. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  48050. // manage pointers
  48051. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  48052. if (pointA === null) {
  48053. pointA = cacheSoloPointer;
  48054. }
  48055. else if (pointB === null) {
  48056. pointB = cacheSoloPointer;
  48057. }
  48058. if (!noPreventDefault) {
  48059. evt.preventDefault();
  48060. element.focus();
  48061. }
  48062. }
  48063. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  48064. _this.camera.restoreState();
  48065. }
  48066. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  48067. try {
  48068. srcElement.releasePointerCapture(evt.pointerId);
  48069. }
  48070. catch (e) {
  48071. //Nothing to do with the error.
  48072. }
  48073. cacheSoloPointer = null;
  48074. previousPinchSquaredDistance = 0;
  48075. previousMultiTouchPanPosition.isPaning = false;
  48076. previousMultiTouchPanPosition.isPinching = false;
  48077. twoFingerActivityCount = 0;
  48078. initialDistance = 0;
  48079. if (!isTouch) {
  48080. pointB = null; // Mouse and pen are mono pointer
  48081. }
  48082. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  48083. //but emptying completly pointers collection is required to fix a bug on iPhone :
  48084. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  48085. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  48086. if (engine._badOS) {
  48087. pointA = pointB = null;
  48088. }
  48089. else {
  48090. //only remove the impacted pointer in case of multitouch allowing on most
  48091. //platforms switching from rotate to zoom and pan seamlessly.
  48092. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  48093. pointA = pointB;
  48094. pointB = null;
  48095. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  48096. }
  48097. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  48098. pointB = null;
  48099. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  48100. }
  48101. else {
  48102. pointA = pointB = null;
  48103. }
  48104. }
  48105. if (!noPreventDefault) {
  48106. evt.preventDefault();
  48107. }
  48108. }
  48109. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  48110. if (!noPreventDefault) {
  48111. evt.preventDefault();
  48112. }
  48113. // One button down
  48114. if (pointA && pointB === null && cacheSoloPointer) {
  48115. if (_this.panningSensibility !== 0 &&
  48116. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  48117. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  48118. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  48119. }
  48120. else {
  48121. var offsetX = evt.clientX - cacheSoloPointer.x;
  48122. var offsetY = evt.clientY - cacheSoloPointer.y;
  48123. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  48124. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  48125. }
  48126. cacheSoloPointer.x = evt.clientX;
  48127. cacheSoloPointer.y = evt.clientY;
  48128. }
  48129. // Two buttons down: pinch/pan
  48130. else if (pointA && pointB) {
  48131. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  48132. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  48133. ed.x = evt.clientX;
  48134. ed.y = evt.clientY;
  48135. var direction = _this.pinchInwards ? 1 : -1;
  48136. var distX = pointA.x - pointB.x;
  48137. var distY = pointA.y - pointB.y;
  48138. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  48139. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  48140. if (previousPinchSquaredDistance === 0) {
  48141. initialDistance = pinchDistance;
  48142. previousPinchSquaredDistance = pinchSquaredDistance;
  48143. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  48144. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  48145. return;
  48146. }
  48147. if (_this.multiTouchPanAndZoom) {
  48148. if (_this.pinchDeltaPercentage) {
  48149. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  48150. }
  48151. else {
  48152. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  48153. (_this.pinchPrecision *
  48154. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  48155. direction);
  48156. }
  48157. if (_this.panningSensibility !== 0) {
  48158. var pointersCenterX = (pointA.x + pointB.x) / 2;
  48159. var pointersCenterY = (pointA.y + pointB.y) / 2;
  48160. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  48161. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  48162. previousMultiTouchPanPosition.x = pointersCenterX;
  48163. previousMultiTouchPanPosition.y = pointersCenterY;
  48164. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  48165. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  48166. }
  48167. }
  48168. else {
  48169. twoFingerActivityCount++;
  48170. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  48171. if (_this.pinchDeltaPercentage) {
  48172. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  48173. }
  48174. else {
  48175. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  48176. (_this.pinchPrecision *
  48177. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  48178. direction);
  48179. }
  48180. previousMultiTouchPanPosition.isPaning = false;
  48181. previousMultiTouchPanPosition.isPinching = true;
  48182. }
  48183. else {
  48184. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  48185. if (!previousMultiTouchPanPosition.isPaning) {
  48186. previousMultiTouchPanPosition.isPaning = true;
  48187. previousMultiTouchPanPosition.isPinching = false;
  48188. previousMultiTouchPanPosition.x = ed.x;
  48189. previousMultiTouchPanPosition.y = ed.y;
  48190. return;
  48191. }
  48192. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  48193. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  48194. }
  48195. }
  48196. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  48197. previousMultiTouchPanPosition.x = ed.x;
  48198. previousMultiTouchPanPosition.y = ed.y;
  48199. }
  48200. }
  48201. previousPinchSquaredDistance = pinchSquaredDistance;
  48202. }
  48203. }
  48204. };
  48205. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  48206. this._onContextMenu = function (evt) {
  48207. evt.preventDefault();
  48208. };
  48209. if (!this.camera._useCtrlForPanning) {
  48210. element.addEventListener("contextmenu", this._onContextMenu, false);
  48211. }
  48212. this._onLostFocus = function () {
  48213. //this._keys = [];
  48214. pointA = pointB = null;
  48215. previousPinchSquaredDistance = 0;
  48216. previousMultiTouchPanPosition.isPaning = false;
  48217. previousMultiTouchPanPosition.isPinching = false;
  48218. twoFingerActivityCount = 0;
  48219. cacheSoloPointer = null;
  48220. initialDistance = 0;
  48221. };
  48222. this._onMouseMove = function (evt) {
  48223. if (!engine.isPointerLock) {
  48224. return;
  48225. }
  48226. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  48227. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  48228. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  48229. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  48230. if (!noPreventDefault) {
  48231. evt.preventDefault();
  48232. }
  48233. };
  48234. this._onGestureStart = function (e) {
  48235. if (window.MSGesture === undefined) {
  48236. return;
  48237. }
  48238. if (!_this._MSGestureHandler) {
  48239. _this._MSGestureHandler = new MSGesture();
  48240. _this._MSGestureHandler.target = element;
  48241. }
  48242. _this._MSGestureHandler.addPointer(e.pointerId);
  48243. };
  48244. this._onGesture = function (e) {
  48245. _this.camera.radius *= e.scale;
  48246. if (e.preventDefault) {
  48247. if (!noPreventDefault) {
  48248. e.stopPropagation();
  48249. e.preventDefault();
  48250. }
  48251. }
  48252. };
  48253. element.addEventListener("mousemove", this._onMouseMove, false);
  48254. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  48255. element.addEventListener("MSGestureChange", this._onGesture, false);
  48256. BABYLON.Tools.RegisterTopRootEvents([
  48257. { name: "blur", handler: this._onLostFocus }
  48258. ]);
  48259. };
  48260. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  48261. if (this._onLostFocus) {
  48262. BABYLON.Tools.UnregisterTopRootEvents([
  48263. { name: "blur", handler: this._onLostFocus }
  48264. ]);
  48265. }
  48266. if (element && this._observer) {
  48267. this.camera.getScene().onPointerObservable.remove(this._observer);
  48268. this._observer = null;
  48269. if (this._onContextMenu) {
  48270. element.removeEventListener("contextmenu", this._onContextMenu);
  48271. }
  48272. if (this._onMouseMove) {
  48273. element.removeEventListener("mousemove", this._onMouseMove);
  48274. }
  48275. if (this._onGestureStart) {
  48276. element.removeEventListener("MSPointerDown", this._onGestureStart);
  48277. }
  48278. if (this._onGesture) {
  48279. element.removeEventListener("MSGestureChange", this._onGesture);
  48280. }
  48281. this._isPanClick = false;
  48282. this.pinchInwards = true;
  48283. this._onMouseMove = null;
  48284. this._onGestureStart = null;
  48285. this._onGesture = null;
  48286. this._MSGestureHandler = null;
  48287. this._onLostFocus = null;
  48288. this._onContextMenu = null;
  48289. }
  48290. };
  48291. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  48292. return "ArcRotateCameraPointersInput";
  48293. };
  48294. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  48295. return "pointers";
  48296. };
  48297. __decorate([
  48298. BABYLON.serialize()
  48299. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  48300. __decorate([
  48301. BABYLON.serialize()
  48302. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  48303. __decorate([
  48304. BABYLON.serialize()
  48305. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  48306. __decorate([
  48307. BABYLON.serialize()
  48308. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  48309. __decorate([
  48310. BABYLON.serialize()
  48311. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  48312. __decorate([
  48313. BABYLON.serialize()
  48314. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  48315. __decorate([
  48316. BABYLON.serialize()
  48317. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  48318. __decorate([
  48319. BABYLON.serialize()
  48320. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  48321. return ArcRotateCameraPointersInput;
  48322. }());
  48323. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  48324. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  48325. })(BABYLON || (BABYLON = {}));
  48326. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  48327. var BABYLON;
  48328. (function (BABYLON) {
  48329. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  48330. __extends(ArcRotateCameraInputsManager, _super);
  48331. function ArcRotateCameraInputsManager(camera) {
  48332. return _super.call(this, camera) || this;
  48333. }
  48334. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  48335. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  48336. return this;
  48337. };
  48338. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  48339. this.add(new BABYLON.ArcRotateCameraPointersInput());
  48340. return this;
  48341. };
  48342. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  48343. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  48344. return this;
  48345. };
  48346. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  48347. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  48348. return this;
  48349. };
  48350. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  48351. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  48352. return this;
  48353. };
  48354. return ArcRotateCameraInputsManager;
  48355. }(BABYLON.CameraInputsManager));
  48356. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  48357. })(BABYLON || (BABYLON = {}));
  48358. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  48359. var BABYLON;
  48360. (function (BABYLON) {
  48361. var ArcRotateCamera = /** @class */ (function (_super) {
  48362. __extends(ArcRotateCamera, _super);
  48363. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  48364. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  48365. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  48366. _this.inertialAlphaOffset = 0;
  48367. _this.inertialBetaOffset = 0;
  48368. _this.inertialRadiusOffset = 0;
  48369. _this.lowerAlphaLimit = null;
  48370. _this.upperAlphaLimit = null;
  48371. _this.lowerBetaLimit = 0.01;
  48372. _this.upperBetaLimit = Math.PI;
  48373. _this.lowerRadiusLimit = null;
  48374. _this.upperRadiusLimit = null;
  48375. _this.inertialPanningX = 0;
  48376. _this.inertialPanningY = 0;
  48377. _this.pinchToPanMaxDistance = 20;
  48378. _this.panningDistanceLimit = null;
  48379. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  48380. _this.panningInertia = 0.9;
  48381. //-- end properties for backward compatibility for inputs
  48382. _this.zoomOnFactor = 1;
  48383. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  48384. _this.allowUpsideDown = true;
  48385. _this._viewMatrix = new BABYLON.Matrix();
  48386. // Panning
  48387. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  48388. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  48389. _this.checkCollisions = false;
  48390. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  48391. _this._previousPosition = BABYLON.Vector3.Zero();
  48392. _this._collisionVelocity = BABYLON.Vector3.Zero();
  48393. _this._newPosition = BABYLON.Vector3.Zero();
  48394. _this._computationVector = BABYLON.Vector3.Zero();
  48395. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  48396. if (collidedMesh === void 0) { collidedMesh = null; }
  48397. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  48398. newPosition.multiplyInPlace(_this._collider._radius);
  48399. }
  48400. if (!collidedMesh) {
  48401. _this._previousPosition.copyFrom(_this.position);
  48402. }
  48403. else {
  48404. _this.setPosition(newPosition);
  48405. if (_this.onCollide) {
  48406. _this.onCollide(collidedMesh);
  48407. }
  48408. }
  48409. // Recompute because of constraints
  48410. var cosa = Math.cos(_this.alpha);
  48411. var sina = Math.sin(_this.alpha);
  48412. var cosb = Math.cos(_this.beta);
  48413. var sinb = Math.sin(_this.beta);
  48414. if (sinb === 0) {
  48415. sinb = 0.0001;
  48416. }
  48417. var target = _this._getTargetPosition();
  48418. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  48419. target.addToRef(_this._computationVector, _this._newPosition);
  48420. _this.position.copyFrom(_this._newPosition);
  48421. var up = _this.upVector;
  48422. if (_this.allowUpsideDown && _this.beta < 0) {
  48423. up = up.clone();
  48424. up = up.negate();
  48425. }
  48426. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  48427. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  48428. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  48429. _this._collisionTriggered = false;
  48430. };
  48431. _this._target = BABYLON.Vector3.Zero();
  48432. if (target) {
  48433. _this.setTarget(target);
  48434. }
  48435. _this.alpha = alpha;
  48436. _this.beta = beta;
  48437. _this.radius = radius;
  48438. _this.getViewMatrix();
  48439. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  48440. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  48441. return _this;
  48442. }
  48443. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  48444. get: function () {
  48445. return this._target;
  48446. },
  48447. set: function (value) {
  48448. this.setTarget(value);
  48449. },
  48450. enumerable: true,
  48451. configurable: true
  48452. });
  48453. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  48454. //-- begin properties for backward compatibility for inputs
  48455. get: function () {
  48456. var pointers = this.inputs.attached["pointers"];
  48457. if (pointers)
  48458. return pointers.angularSensibilityX;
  48459. return 0;
  48460. },
  48461. set: function (value) {
  48462. var pointers = this.inputs.attached["pointers"];
  48463. if (pointers) {
  48464. pointers.angularSensibilityX = value;
  48465. }
  48466. },
  48467. enumerable: true,
  48468. configurable: true
  48469. });
  48470. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  48471. get: function () {
  48472. var pointers = this.inputs.attached["pointers"];
  48473. if (pointers)
  48474. return pointers.angularSensibilityY;
  48475. return 0;
  48476. },
  48477. set: function (value) {
  48478. var pointers = this.inputs.attached["pointers"];
  48479. if (pointers) {
  48480. pointers.angularSensibilityY = value;
  48481. }
  48482. },
  48483. enumerable: true,
  48484. configurable: true
  48485. });
  48486. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  48487. get: function () {
  48488. var pointers = this.inputs.attached["pointers"];
  48489. if (pointers)
  48490. return pointers.pinchPrecision;
  48491. return 0;
  48492. },
  48493. set: function (value) {
  48494. var pointers = this.inputs.attached["pointers"];
  48495. if (pointers) {
  48496. pointers.pinchPrecision = value;
  48497. }
  48498. },
  48499. enumerable: true,
  48500. configurable: true
  48501. });
  48502. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  48503. get: function () {
  48504. var pointers = this.inputs.attached["pointers"];
  48505. if (pointers)
  48506. return pointers.pinchDeltaPercentage;
  48507. return 0;
  48508. },
  48509. set: function (value) {
  48510. var pointers = this.inputs.attached["pointers"];
  48511. if (pointers) {
  48512. pointers.pinchDeltaPercentage = value;
  48513. }
  48514. },
  48515. enumerable: true,
  48516. configurable: true
  48517. });
  48518. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  48519. get: function () {
  48520. var pointers = this.inputs.attached["pointers"];
  48521. if (pointers)
  48522. return pointers.panningSensibility;
  48523. return 0;
  48524. },
  48525. set: function (value) {
  48526. var pointers = this.inputs.attached["pointers"];
  48527. if (pointers) {
  48528. pointers.panningSensibility = value;
  48529. }
  48530. },
  48531. enumerable: true,
  48532. configurable: true
  48533. });
  48534. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  48535. get: function () {
  48536. var keyboard = this.inputs.attached["keyboard"];
  48537. if (keyboard)
  48538. return keyboard.keysUp;
  48539. return [];
  48540. },
  48541. set: function (value) {
  48542. var keyboard = this.inputs.attached["keyboard"];
  48543. if (keyboard)
  48544. keyboard.keysUp = value;
  48545. },
  48546. enumerable: true,
  48547. configurable: true
  48548. });
  48549. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  48550. get: function () {
  48551. var keyboard = this.inputs.attached["keyboard"];
  48552. if (keyboard)
  48553. return keyboard.keysDown;
  48554. return [];
  48555. },
  48556. set: function (value) {
  48557. var keyboard = this.inputs.attached["keyboard"];
  48558. if (keyboard)
  48559. keyboard.keysDown = value;
  48560. },
  48561. enumerable: true,
  48562. configurable: true
  48563. });
  48564. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  48565. get: function () {
  48566. var keyboard = this.inputs.attached["keyboard"];
  48567. if (keyboard)
  48568. return keyboard.keysLeft;
  48569. return [];
  48570. },
  48571. set: function (value) {
  48572. var keyboard = this.inputs.attached["keyboard"];
  48573. if (keyboard)
  48574. keyboard.keysLeft = value;
  48575. },
  48576. enumerable: true,
  48577. configurable: true
  48578. });
  48579. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  48580. get: function () {
  48581. var keyboard = this.inputs.attached["keyboard"];
  48582. if (keyboard)
  48583. return keyboard.keysRight;
  48584. return [];
  48585. },
  48586. set: function (value) {
  48587. var keyboard = this.inputs.attached["keyboard"];
  48588. if (keyboard)
  48589. keyboard.keysRight = value;
  48590. },
  48591. enumerable: true,
  48592. configurable: true
  48593. });
  48594. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  48595. get: function () {
  48596. var mousewheel = this.inputs.attached["mousewheel"];
  48597. if (mousewheel)
  48598. return mousewheel.wheelPrecision;
  48599. return 0;
  48600. },
  48601. set: function (value) {
  48602. var mousewheel = this.inputs.attached["mousewheel"];
  48603. if (mousewheel)
  48604. mousewheel.wheelPrecision = value;
  48605. },
  48606. enumerable: true,
  48607. configurable: true
  48608. });
  48609. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  48610. get: function () {
  48611. var mousewheel = this.inputs.attached["mousewheel"];
  48612. if (mousewheel)
  48613. return mousewheel.wheelDeltaPercentage;
  48614. return 0;
  48615. },
  48616. set: function (value) {
  48617. var mousewheel = this.inputs.attached["mousewheel"];
  48618. if (mousewheel)
  48619. mousewheel.wheelDeltaPercentage = value;
  48620. },
  48621. enumerable: true,
  48622. configurable: true
  48623. });
  48624. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  48625. get: function () {
  48626. return this._bouncingBehavior;
  48627. },
  48628. enumerable: true,
  48629. configurable: true
  48630. });
  48631. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  48632. get: function () {
  48633. return this._bouncingBehavior != null;
  48634. },
  48635. set: function (value) {
  48636. if (value === this.useBouncingBehavior) {
  48637. return;
  48638. }
  48639. if (value) {
  48640. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  48641. this.addBehavior(this._bouncingBehavior);
  48642. }
  48643. else if (this._bouncingBehavior) {
  48644. this.removeBehavior(this._bouncingBehavior);
  48645. this._bouncingBehavior = null;
  48646. }
  48647. },
  48648. enumerable: true,
  48649. configurable: true
  48650. });
  48651. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  48652. get: function () {
  48653. return this._framingBehavior;
  48654. },
  48655. enumerable: true,
  48656. configurable: true
  48657. });
  48658. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  48659. get: function () {
  48660. return this._framingBehavior != null;
  48661. },
  48662. set: function (value) {
  48663. if (value === this.useFramingBehavior) {
  48664. return;
  48665. }
  48666. if (value) {
  48667. this._framingBehavior = new BABYLON.FramingBehavior();
  48668. this.addBehavior(this._framingBehavior);
  48669. }
  48670. else if (this._framingBehavior) {
  48671. this.removeBehavior(this._framingBehavior);
  48672. this._framingBehavior = null;
  48673. }
  48674. },
  48675. enumerable: true,
  48676. configurable: true
  48677. });
  48678. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  48679. get: function () {
  48680. return this._autoRotationBehavior;
  48681. },
  48682. enumerable: true,
  48683. configurable: true
  48684. });
  48685. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  48686. get: function () {
  48687. return this._autoRotationBehavior != null;
  48688. },
  48689. set: function (value) {
  48690. if (value === this.useAutoRotationBehavior) {
  48691. return;
  48692. }
  48693. if (value) {
  48694. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  48695. this.addBehavior(this._autoRotationBehavior);
  48696. }
  48697. else if (this._autoRotationBehavior) {
  48698. this.removeBehavior(this._autoRotationBehavior);
  48699. this._autoRotationBehavior = null;
  48700. }
  48701. },
  48702. enumerable: true,
  48703. configurable: true
  48704. });
  48705. // Cache
  48706. ArcRotateCamera.prototype._initCache = function () {
  48707. _super.prototype._initCache.call(this);
  48708. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  48709. this._cache.alpha = undefined;
  48710. this._cache.beta = undefined;
  48711. this._cache.radius = undefined;
  48712. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  48713. };
  48714. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  48715. if (!ignoreParentClass) {
  48716. _super.prototype._updateCache.call(this);
  48717. }
  48718. this._cache._target.copyFrom(this._getTargetPosition());
  48719. this._cache.alpha = this.alpha;
  48720. this._cache.beta = this.beta;
  48721. this._cache.radius = this.radius;
  48722. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  48723. };
  48724. ArcRotateCamera.prototype._getTargetPosition = function () {
  48725. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  48726. var pos = this._targetHost.getAbsolutePosition();
  48727. if (this._targetBoundingCenter) {
  48728. pos.addToRef(this._targetBoundingCenter, this._target);
  48729. }
  48730. else {
  48731. this._target.copyFrom(pos);
  48732. }
  48733. }
  48734. var lockedTargetPosition = this._getLockedTargetPosition();
  48735. if (lockedTargetPosition) {
  48736. return lockedTargetPosition;
  48737. }
  48738. return this._target;
  48739. };
  48740. ArcRotateCamera.prototype.storeState = function () {
  48741. this._storedAlpha = this.alpha;
  48742. this._storedBeta = this.beta;
  48743. this._storedRadius = this.radius;
  48744. this._storedTarget = this._getTargetPosition().clone();
  48745. return _super.prototype.storeState.call(this);
  48746. };
  48747. /**
  48748. * Restored camera state. You must call storeState() first
  48749. */
  48750. ArcRotateCamera.prototype._restoreStateValues = function () {
  48751. if (!_super.prototype._restoreStateValues.call(this)) {
  48752. return false;
  48753. }
  48754. this.alpha = this._storedAlpha;
  48755. this.beta = this._storedBeta;
  48756. this.radius = this._storedRadius;
  48757. this.setTarget(this._storedTarget.clone());
  48758. this.inertialAlphaOffset = 0;
  48759. this.inertialBetaOffset = 0;
  48760. this.inertialRadiusOffset = 0;
  48761. this.inertialPanningX = 0;
  48762. this.inertialPanningY = 0;
  48763. return true;
  48764. };
  48765. // Synchronized
  48766. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  48767. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  48768. return false;
  48769. return this._cache._target.equals(this._getTargetPosition())
  48770. && this._cache.alpha === this.alpha
  48771. && this._cache.beta === this.beta
  48772. && this._cache.radius === this.radius
  48773. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  48774. };
  48775. // Methods
  48776. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  48777. var _this = this;
  48778. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  48779. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  48780. this._useCtrlForPanning = useCtrlForPanning;
  48781. this._panningMouseButton = panningMouseButton;
  48782. this.inputs.attachElement(element, noPreventDefault);
  48783. this._reset = function () {
  48784. _this.inertialAlphaOffset = 0;
  48785. _this.inertialBetaOffset = 0;
  48786. _this.inertialRadiusOffset = 0;
  48787. _this.inertialPanningX = 0;
  48788. _this.inertialPanningY = 0;
  48789. };
  48790. };
  48791. ArcRotateCamera.prototype.detachControl = function (element) {
  48792. this.inputs.detachElement(element);
  48793. if (this._reset) {
  48794. this._reset();
  48795. }
  48796. };
  48797. ArcRotateCamera.prototype._checkInputs = function () {
  48798. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  48799. if (this._collisionTriggered) {
  48800. return;
  48801. }
  48802. this.inputs.checkInputs();
  48803. // Inertia
  48804. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  48805. var inertialAlphaOffset = this.inertialAlphaOffset;
  48806. if (this.beta <= 0)
  48807. inertialAlphaOffset *= -1;
  48808. if (this.getScene().useRightHandedSystem)
  48809. inertialAlphaOffset *= -1;
  48810. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  48811. inertialAlphaOffset *= -1;
  48812. this.alpha += inertialAlphaOffset;
  48813. this.beta += this.inertialBetaOffset;
  48814. this.radius -= this.inertialRadiusOffset;
  48815. this.inertialAlphaOffset *= this.inertia;
  48816. this.inertialBetaOffset *= this.inertia;
  48817. this.inertialRadiusOffset *= this.inertia;
  48818. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  48819. this.inertialAlphaOffset = 0;
  48820. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  48821. this.inertialBetaOffset = 0;
  48822. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  48823. this.inertialRadiusOffset = 0;
  48824. }
  48825. // Panning inertia
  48826. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  48827. if (!this._localDirection) {
  48828. this._localDirection = BABYLON.Vector3.Zero();
  48829. this._transformedDirection = BABYLON.Vector3.Zero();
  48830. }
  48831. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  48832. this._localDirection.multiplyInPlace(this.panningAxis);
  48833. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  48834. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  48835. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  48836. if (!this.panningAxis.y) {
  48837. this._transformedDirection.y = 0;
  48838. }
  48839. if (!this._targetHost) {
  48840. if (this.panningDistanceLimit) {
  48841. this._transformedDirection.addInPlace(this._target);
  48842. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  48843. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  48844. this._target.copyFrom(this._transformedDirection);
  48845. }
  48846. }
  48847. else {
  48848. this._target.addInPlace(this._transformedDirection);
  48849. }
  48850. }
  48851. this.inertialPanningX *= this.panningInertia;
  48852. this.inertialPanningY *= this.panningInertia;
  48853. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  48854. this.inertialPanningX = 0;
  48855. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  48856. this.inertialPanningY = 0;
  48857. }
  48858. // Limits
  48859. this._checkLimits();
  48860. _super.prototype._checkInputs.call(this);
  48861. };
  48862. ArcRotateCamera.prototype._checkLimits = function () {
  48863. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  48864. if (this.allowUpsideDown && this.beta > Math.PI) {
  48865. this.beta = this.beta - (2 * Math.PI);
  48866. }
  48867. }
  48868. else {
  48869. if (this.beta < this.lowerBetaLimit) {
  48870. this.beta = this.lowerBetaLimit;
  48871. }
  48872. }
  48873. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  48874. if (this.allowUpsideDown && this.beta < -Math.PI) {
  48875. this.beta = this.beta + (2 * Math.PI);
  48876. }
  48877. }
  48878. else {
  48879. if (this.beta > this.upperBetaLimit) {
  48880. this.beta = this.upperBetaLimit;
  48881. }
  48882. }
  48883. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  48884. this.alpha = this.lowerAlphaLimit;
  48885. }
  48886. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  48887. this.alpha = this.upperAlphaLimit;
  48888. }
  48889. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  48890. this.radius = this.lowerRadiusLimit;
  48891. }
  48892. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  48893. this.radius = this.upperRadiusLimit;
  48894. }
  48895. };
  48896. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  48897. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  48898. this.radius = this._computationVector.length();
  48899. if (this.radius === 0) {
  48900. this.radius = 0.0001; // Just to avoid division by zero
  48901. }
  48902. // Alpha
  48903. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  48904. if (this._computationVector.z < 0) {
  48905. this.alpha = 2 * Math.PI - this.alpha;
  48906. }
  48907. // Beta
  48908. this.beta = Math.acos(this._computationVector.y / this.radius);
  48909. this._checkLimits();
  48910. };
  48911. ArcRotateCamera.prototype.setPosition = function (position) {
  48912. if (this.position.equals(position)) {
  48913. return;
  48914. }
  48915. this.position.copyFrom(position);
  48916. this.rebuildAnglesAndRadius();
  48917. };
  48918. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  48919. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  48920. if (allowSamePosition === void 0) { allowSamePosition = false; }
  48921. if (target.getBoundingInfo) {
  48922. if (toBoundingCenter) {
  48923. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  48924. }
  48925. else {
  48926. this._targetBoundingCenter = null;
  48927. }
  48928. this._targetHost = target;
  48929. this._target = this._getTargetPosition();
  48930. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  48931. }
  48932. else {
  48933. var newTarget = target;
  48934. var currentTarget = this._getTargetPosition();
  48935. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  48936. return;
  48937. }
  48938. this._targetHost = null;
  48939. this._target = newTarget;
  48940. this._targetBoundingCenter = null;
  48941. this.onMeshTargetChangedObservable.notifyObservers(null);
  48942. }
  48943. this.rebuildAnglesAndRadius();
  48944. };
  48945. ArcRotateCamera.prototype._getViewMatrix = function () {
  48946. // Compute
  48947. var cosa = Math.cos(this.alpha);
  48948. var sina = Math.sin(this.alpha);
  48949. var cosb = Math.cos(this.beta);
  48950. var sinb = Math.sin(this.beta);
  48951. if (sinb === 0) {
  48952. sinb = 0.0001;
  48953. }
  48954. var target = this._getTargetPosition();
  48955. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  48956. target.addToRef(this._computationVector, this._newPosition);
  48957. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  48958. if (!this._collider) {
  48959. this._collider = new BABYLON.Collider();
  48960. }
  48961. this._collider._radius = this.collisionRadius;
  48962. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  48963. this._collisionTriggered = true;
  48964. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  48965. }
  48966. else {
  48967. this.position.copyFrom(this._newPosition);
  48968. var up = this.upVector;
  48969. if (this.allowUpsideDown && sinb < 0) {
  48970. up = up.clone();
  48971. up = up.negate();
  48972. }
  48973. this._computeViewMatrix(this.position, target, up);
  48974. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  48975. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  48976. }
  48977. this._currentTarget = target;
  48978. return this._viewMatrix;
  48979. };
  48980. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  48981. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48982. meshes = meshes || this.getScene().meshes;
  48983. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  48984. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  48985. this.radius = distance * this.zoomOnFactor;
  48986. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  48987. };
  48988. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  48989. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48990. var meshesOrMinMaxVector;
  48991. var distance;
  48992. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  48993. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  48994. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  48995. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  48996. }
  48997. else { //minMaxVector and distance
  48998. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  48999. meshesOrMinMaxVector = minMaxVectorAndDistance;
  49000. distance = minMaxVectorAndDistance.distance;
  49001. }
  49002. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  49003. if (!doNotUpdateMaxZ) {
  49004. this.maxZ = distance * 2;
  49005. }
  49006. };
  49007. /**
  49008. * @override
  49009. * Override Camera.createRigCamera
  49010. */
  49011. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  49012. var alphaShift = 0;
  49013. switch (this.cameraRigMode) {
  49014. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  49015. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  49016. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  49017. case BABYLON.Camera.RIG_MODE_VR:
  49018. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  49019. break;
  49020. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  49021. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  49022. break;
  49023. }
  49024. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  49025. rigCam._cameraRigParams = {};
  49026. return rigCam;
  49027. };
  49028. /**
  49029. * @override
  49030. * Override Camera._updateRigCameras
  49031. */
  49032. ArcRotateCamera.prototype._updateRigCameras = function () {
  49033. var camLeft = this._rigCameras[0];
  49034. var camRight = this._rigCameras[1];
  49035. camLeft.beta = camRight.beta = this.beta;
  49036. camLeft.radius = camRight.radius = this.radius;
  49037. switch (this.cameraRigMode) {
  49038. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  49039. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  49040. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  49041. case BABYLON.Camera.RIG_MODE_VR:
  49042. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  49043. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  49044. break;
  49045. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  49046. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  49047. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  49048. break;
  49049. }
  49050. _super.prototype._updateRigCameras.call(this);
  49051. };
  49052. ArcRotateCamera.prototype.dispose = function () {
  49053. this.inputs.clear();
  49054. _super.prototype.dispose.call(this);
  49055. };
  49056. ArcRotateCamera.prototype.getClassName = function () {
  49057. return "ArcRotateCamera";
  49058. };
  49059. __decorate([
  49060. BABYLON.serialize()
  49061. ], ArcRotateCamera.prototype, "alpha", void 0);
  49062. __decorate([
  49063. BABYLON.serialize()
  49064. ], ArcRotateCamera.prototype, "beta", void 0);
  49065. __decorate([
  49066. BABYLON.serialize()
  49067. ], ArcRotateCamera.prototype, "radius", void 0);
  49068. __decorate([
  49069. BABYLON.serializeAsVector3("target")
  49070. ], ArcRotateCamera.prototype, "_target", void 0);
  49071. __decorate([
  49072. BABYLON.serialize()
  49073. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  49074. __decorate([
  49075. BABYLON.serialize()
  49076. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  49077. __decorate([
  49078. BABYLON.serialize()
  49079. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  49080. __decorate([
  49081. BABYLON.serialize()
  49082. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  49083. __decorate([
  49084. BABYLON.serialize()
  49085. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  49086. __decorate([
  49087. BABYLON.serialize()
  49088. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  49089. __decorate([
  49090. BABYLON.serialize()
  49091. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  49092. __decorate([
  49093. BABYLON.serialize()
  49094. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  49095. __decorate([
  49096. BABYLON.serialize()
  49097. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  49098. __decorate([
  49099. BABYLON.serialize()
  49100. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  49101. __decorate([
  49102. BABYLON.serialize()
  49103. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  49104. __decorate([
  49105. BABYLON.serialize()
  49106. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  49107. __decorate([
  49108. BABYLON.serialize()
  49109. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  49110. __decorate([
  49111. BABYLON.serializeAsVector3()
  49112. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  49113. __decorate([
  49114. BABYLON.serialize()
  49115. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  49116. __decorate([
  49117. BABYLON.serialize()
  49118. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  49119. __decorate([
  49120. BABYLON.serialize()
  49121. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  49122. return ArcRotateCamera;
  49123. }(BABYLON.TargetCamera));
  49124. BABYLON.ArcRotateCamera = ArcRotateCamera;
  49125. })(BABYLON || (BABYLON = {}));
  49126. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  49127. var BABYLON;
  49128. (function (BABYLON) {
  49129. /**
  49130. * The HemisphericLight simulates the ambient environment light,
  49131. * so the passed direction is the light reflection direction, not the incoming direction.
  49132. */
  49133. var HemisphericLight = /** @class */ (function (_super) {
  49134. __extends(HemisphericLight, _super);
  49135. /**
  49136. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  49137. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  49138. * The HemisphericLight can't cast shadows.
  49139. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49140. * @param name The friendly name of the light
  49141. * @param direction The direction of the light reflection
  49142. * @param scene The scene the light belongs to
  49143. */
  49144. function HemisphericLight(name, direction, scene) {
  49145. var _this = _super.call(this, name, scene) || this;
  49146. /**
  49147. * The groundColor is the light in the opposite direction to the one specified during creation.
  49148. * 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.
  49149. */
  49150. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  49151. _this.direction = direction || BABYLON.Vector3.Up();
  49152. return _this;
  49153. }
  49154. HemisphericLight.prototype._buildUniformLayout = function () {
  49155. this._uniformBuffer.addUniform("vLightData", 4);
  49156. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49157. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49158. this._uniformBuffer.addUniform("vLightGround", 3);
  49159. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49160. this._uniformBuffer.addUniform("depthValues", 2);
  49161. this._uniformBuffer.create();
  49162. };
  49163. /**
  49164. * Returns the string "HemisphericLight".
  49165. * @return The class name
  49166. */
  49167. HemisphericLight.prototype.getClassName = function () {
  49168. return "HemisphericLight";
  49169. };
  49170. /**
  49171. * Sets the HemisphericLight direction towards the passed target (Vector3).
  49172. * Returns the updated direction.
  49173. * @param target The target the direction should point to
  49174. * @return The computed direction
  49175. */
  49176. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  49177. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  49178. return this.direction;
  49179. };
  49180. /**
  49181. * Returns the shadow generator associated to the light.
  49182. * @returns Always null for hemispheric lights because it does not support shadows.
  49183. */
  49184. HemisphericLight.prototype.getShadowGenerator = function () {
  49185. return null;
  49186. };
  49187. /**
  49188. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  49189. * @param effect The effect to update
  49190. * @param lightIndex The index of the light in the effect to update
  49191. * @returns The hemispheric light
  49192. */
  49193. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  49194. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49195. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  49196. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  49197. return this;
  49198. };
  49199. /**
  49200. * @hidden internal use only.
  49201. */
  49202. HemisphericLight.prototype._getWorldMatrix = function () {
  49203. if (!this._worldMatrix) {
  49204. this._worldMatrix = BABYLON.Matrix.Identity();
  49205. }
  49206. return this._worldMatrix;
  49207. };
  49208. /**
  49209. * Returns the integer 3.
  49210. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49211. */
  49212. HemisphericLight.prototype.getTypeID = function () {
  49213. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  49214. };
  49215. __decorate([
  49216. BABYLON.serializeAsColor3()
  49217. ], HemisphericLight.prototype, "groundColor", void 0);
  49218. __decorate([
  49219. BABYLON.serializeAsVector3()
  49220. ], HemisphericLight.prototype, "direction", void 0);
  49221. return HemisphericLight;
  49222. }(BABYLON.Light));
  49223. BABYLON.HemisphericLight = HemisphericLight;
  49224. })(BABYLON || (BABYLON = {}));
  49225. //# sourceMappingURL=babylon.hemisphericLight.js.map
  49226. var BABYLON;
  49227. (function (BABYLON) {
  49228. /**
  49229. * Base implementation IShadowLight
  49230. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  49231. */
  49232. var ShadowLight = /** @class */ (function (_super) {
  49233. __extends(ShadowLight, _super);
  49234. function ShadowLight() {
  49235. var _this = _super !== null && _super.apply(this, arguments) || this;
  49236. _this._needProjectionMatrixCompute = true;
  49237. return _this;
  49238. }
  49239. ShadowLight.prototype._setPosition = function (value) {
  49240. this._position = value;
  49241. };
  49242. Object.defineProperty(ShadowLight.prototype, "position", {
  49243. /**
  49244. * Sets the position the shadow will be casted from. Also use as the light position for both
  49245. * point and spot lights.
  49246. */
  49247. get: function () {
  49248. return this._position;
  49249. },
  49250. /**
  49251. * Sets the position the shadow will be casted from. Also use as the light position for both
  49252. * point and spot lights.
  49253. */
  49254. set: function (value) {
  49255. this._setPosition(value);
  49256. },
  49257. enumerable: true,
  49258. configurable: true
  49259. });
  49260. ShadowLight.prototype._setDirection = function (value) {
  49261. this._direction = value;
  49262. };
  49263. Object.defineProperty(ShadowLight.prototype, "direction", {
  49264. /**
  49265. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  49266. * Also use as the light direction on spot and directional lights.
  49267. */
  49268. get: function () {
  49269. return this._direction;
  49270. },
  49271. /**
  49272. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  49273. * Also use as the light direction on spot and directional lights.
  49274. */
  49275. set: function (value) {
  49276. this._setDirection(value);
  49277. },
  49278. enumerable: true,
  49279. configurable: true
  49280. });
  49281. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  49282. /**
  49283. * Gets the shadow projection clipping minimum z value.
  49284. */
  49285. get: function () {
  49286. return this._shadowMinZ;
  49287. },
  49288. /**
  49289. * Sets the shadow projection clipping minimum z value.
  49290. */
  49291. set: function (value) {
  49292. this._shadowMinZ = value;
  49293. this.forceProjectionMatrixCompute();
  49294. },
  49295. enumerable: true,
  49296. configurable: true
  49297. });
  49298. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  49299. /**
  49300. * Sets the shadow projection clipping maximum z value.
  49301. */
  49302. get: function () {
  49303. return this._shadowMaxZ;
  49304. },
  49305. /**
  49306. * Gets the shadow projection clipping maximum z value.
  49307. */
  49308. set: function (value) {
  49309. this._shadowMaxZ = value;
  49310. this.forceProjectionMatrixCompute();
  49311. },
  49312. enumerable: true,
  49313. configurable: true
  49314. });
  49315. /**
  49316. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  49317. * @returns true if the information has been computed, false if it does not need to (no parenting)
  49318. */
  49319. ShadowLight.prototype.computeTransformedInformation = function () {
  49320. if (this.parent && this.parent.getWorldMatrix) {
  49321. if (!this.transformedPosition) {
  49322. this.transformedPosition = BABYLON.Vector3.Zero();
  49323. }
  49324. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  49325. // In case the direction is present.
  49326. if (this.direction) {
  49327. if (!this.transformedDirection) {
  49328. this.transformedDirection = BABYLON.Vector3.Zero();
  49329. }
  49330. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  49331. }
  49332. return true;
  49333. }
  49334. return false;
  49335. };
  49336. /**
  49337. * Return the depth scale used for the shadow map.
  49338. * @returns the depth scale.
  49339. */
  49340. ShadowLight.prototype.getDepthScale = function () {
  49341. return 50.0;
  49342. };
  49343. /**
  49344. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  49345. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49346. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49347. */
  49348. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  49349. return this.transformedDirection ? this.transformedDirection : this.direction;
  49350. };
  49351. /**
  49352. * Returns the ShadowLight absolute position in the World.
  49353. * @returns the position vector in world space
  49354. */
  49355. ShadowLight.prototype.getAbsolutePosition = function () {
  49356. return this.transformedPosition ? this.transformedPosition : this.position;
  49357. };
  49358. /**
  49359. * Sets the ShadowLight direction toward the passed target.
  49360. * @param target The point tot target in local space
  49361. * @returns the updated ShadowLight direction
  49362. */
  49363. ShadowLight.prototype.setDirectionToTarget = function (target) {
  49364. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  49365. return this.direction;
  49366. };
  49367. /**
  49368. * Returns the light rotation in euler definition.
  49369. * @returns the x y z rotation in local space.
  49370. */
  49371. ShadowLight.prototype.getRotation = function () {
  49372. this.direction.normalize();
  49373. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  49374. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  49375. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  49376. };
  49377. /**
  49378. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  49379. * @returns true if a cube texture needs to be use
  49380. */
  49381. ShadowLight.prototype.needCube = function () {
  49382. return false;
  49383. };
  49384. /**
  49385. * Detects if the projection matrix requires to be recomputed this frame.
  49386. * @returns true if it requires to be recomputed otherwise, false.
  49387. */
  49388. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  49389. return this._needProjectionMatrixCompute;
  49390. };
  49391. /**
  49392. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  49393. */
  49394. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  49395. this._needProjectionMatrixCompute = true;
  49396. };
  49397. /**
  49398. * Get the world matrix of the sahdow lights.
  49399. * @hidden Internal Use Only
  49400. */
  49401. ShadowLight.prototype._getWorldMatrix = function () {
  49402. if (!this._worldMatrix) {
  49403. this._worldMatrix = BABYLON.Matrix.Identity();
  49404. }
  49405. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  49406. return this._worldMatrix;
  49407. };
  49408. /**
  49409. * Gets the minZ used for shadow according to both the scene and the light.
  49410. * @param activeCamera The camera we are returning the min for
  49411. * @returns the depth min z
  49412. */
  49413. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  49414. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  49415. };
  49416. /**
  49417. * Gets the maxZ used for shadow according to both the scene and the light.
  49418. * @param activeCamera The camera we are returning the max for
  49419. * @returns the depth max z
  49420. */
  49421. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  49422. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  49423. };
  49424. /**
  49425. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  49426. * @param matrix The materix to updated with the projection information
  49427. * @param viewMatrix The transform matrix of the light
  49428. * @param renderList The list of mesh to render in the map
  49429. * @returns The current light
  49430. */
  49431. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49432. if (this.customProjectionMatrixBuilder) {
  49433. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  49434. }
  49435. else {
  49436. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49437. }
  49438. return this;
  49439. };
  49440. __decorate([
  49441. BABYLON.serializeAsVector3()
  49442. ], ShadowLight.prototype, "position", null);
  49443. __decorate([
  49444. BABYLON.serializeAsVector3()
  49445. ], ShadowLight.prototype, "direction", null);
  49446. __decorate([
  49447. BABYLON.serialize()
  49448. ], ShadowLight.prototype, "shadowMinZ", null);
  49449. __decorate([
  49450. BABYLON.serialize()
  49451. ], ShadowLight.prototype, "shadowMaxZ", null);
  49452. return ShadowLight;
  49453. }(BABYLON.Light));
  49454. BABYLON.ShadowLight = ShadowLight;
  49455. })(BABYLON || (BABYLON = {}));
  49456. //# sourceMappingURL=babylon.shadowLight.js.map
  49457. var BABYLON;
  49458. (function (BABYLON) {
  49459. /**
  49460. * A point light is a light defined by an unique point in world space.
  49461. * The light is emitted in every direction from this point.
  49462. * A good example of a point light is a standard light bulb.
  49463. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49464. */
  49465. var PointLight = /** @class */ (function (_super) {
  49466. __extends(PointLight, _super);
  49467. /**
  49468. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  49469. * A PointLight emits the light in every direction.
  49470. * It can cast shadows.
  49471. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  49472. * ```javascript
  49473. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  49474. * ```
  49475. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49476. * @param name The light friendly name
  49477. * @param position The position of the point light in the scene
  49478. * @param scene The scene the lights belongs to
  49479. */
  49480. function PointLight(name, position, scene) {
  49481. var _this = _super.call(this, name, scene) || this;
  49482. _this._shadowAngle = Math.PI / 2;
  49483. _this.position = position;
  49484. return _this;
  49485. }
  49486. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  49487. /**
  49488. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49489. * This specifies what angle the shadow will use to be created.
  49490. *
  49491. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49492. */
  49493. get: function () {
  49494. return this._shadowAngle;
  49495. },
  49496. /**
  49497. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49498. * This specifies what angle the shadow will use to be created.
  49499. *
  49500. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49501. */
  49502. set: function (value) {
  49503. this._shadowAngle = value;
  49504. this.forceProjectionMatrixCompute();
  49505. },
  49506. enumerable: true,
  49507. configurable: true
  49508. });
  49509. Object.defineProperty(PointLight.prototype, "direction", {
  49510. /**
  49511. * Gets the direction if it has been set.
  49512. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49513. */
  49514. get: function () {
  49515. return this._direction;
  49516. },
  49517. /**
  49518. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49519. */
  49520. set: function (value) {
  49521. var previousNeedCube = this.needCube();
  49522. this._direction = value;
  49523. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  49524. this._shadowGenerator.recreateShadowMap();
  49525. }
  49526. },
  49527. enumerable: true,
  49528. configurable: true
  49529. });
  49530. /**
  49531. * Returns the string "PointLight"
  49532. * @returns the class name
  49533. */
  49534. PointLight.prototype.getClassName = function () {
  49535. return "PointLight";
  49536. };
  49537. /**
  49538. * Returns the integer 0.
  49539. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49540. */
  49541. PointLight.prototype.getTypeID = function () {
  49542. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  49543. };
  49544. /**
  49545. * Specifies wether or not the shadowmap should be a cube texture.
  49546. * @returns true if the shadowmap needs to be a cube texture.
  49547. */
  49548. PointLight.prototype.needCube = function () {
  49549. return !this.direction;
  49550. };
  49551. /**
  49552. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  49553. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49554. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49555. */
  49556. PointLight.prototype.getShadowDirection = function (faceIndex) {
  49557. if (this.direction) {
  49558. return _super.prototype.getShadowDirection.call(this, faceIndex);
  49559. }
  49560. else {
  49561. switch (faceIndex) {
  49562. case 0:
  49563. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  49564. case 1:
  49565. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  49566. case 2:
  49567. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  49568. case 3:
  49569. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  49570. case 4:
  49571. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  49572. case 5:
  49573. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  49574. }
  49575. }
  49576. return BABYLON.Vector3.Zero();
  49577. };
  49578. /**
  49579. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  49580. * - fov = PI / 2
  49581. * - aspect ratio : 1.0
  49582. * - z-near and far equal to the active camera minZ and maxZ.
  49583. * Returns the PointLight.
  49584. */
  49585. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49586. var activeCamera = this.getScene().activeCamera;
  49587. if (!activeCamera) {
  49588. return;
  49589. }
  49590. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49591. };
  49592. PointLight.prototype._buildUniformLayout = function () {
  49593. this._uniformBuffer.addUniform("vLightData", 4);
  49594. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49595. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49596. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49597. this._uniformBuffer.addUniform("depthValues", 2);
  49598. this._uniformBuffer.create();
  49599. };
  49600. /**
  49601. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  49602. * @param effect The effect to update
  49603. * @param lightIndex The index of the light in the effect to update
  49604. * @returns The point light
  49605. */
  49606. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  49607. if (this.computeTransformedInformation()) {
  49608. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  49609. return this;
  49610. }
  49611. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  49612. return this;
  49613. };
  49614. __decorate([
  49615. BABYLON.serialize()
  49616. ], PointLight.prototype, "shadowAngle", null);
  49617. return PointLight;
  49618. }(BABYLON.ShadowLight));
  49619. BABYLON.PointLight = PointLight;
  49620. })(BABYLON || (BABYLON = {}));
  49621. //# sourceMappingURL=babylon.pointLight.js.map
  49622. var BABYLON;
  49623. (function (BABYLON) {
  49624. /**
  49625. * A directional light is defined by a direction (what a surprise!).
  49626. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  49627. * 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.
  49628. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49629. */
  49630. var DirectionalLight = /** @class */ (function (_super) {
  49631. __extends(DirectionalLight, _super);
  49632. /**
  49633. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  49634. * The directional light is emitted from everywhere in the given direction.
  49635. * It can cast shawdows.
  49636. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49637. * @param name The friendly name of the light
  49638. * @param direction The direction of the light
  49639. * @param scene The scene the light belongs to
  49640. */
  49641. function DirectionalLight(name, direction, scene) {
  49642. var _this = _super.call(this, name, scene) || this;
  49643. _this._shadowFrustumSize = 0;
  49644. _this._shadowOrthoScale = 0.1;
  49645. /**
  49646. * Automatically compute the projection matrix to best fit (including all the casters)
  49647. * on each frame.
  49648. */
  49649. _this.autoUpdateExtends = true;
  49650. // Cache
  49651. _this._orthoLeft = Number.MAX_VALUE;
  49652. _this._orthoRight = Number.MIN_VALUE;
  49653. _this._orthoTop = Number.MIN_VALUE;
  49654. _this._orthoBottom = Number.MAX_VALUE;
  49655. _this.position = direction.scale(-1.0);
  49656. _this.direction = direction;
  49657. return _this;
  49658. }
  49659. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  49660. /**
  49661. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  49662. */
  49663. get: function () {
  49664. return this._shadowFrustumSize;
  49665. },
  49666. /**
  49667. * Specifies a fix frustum size for the shadow generation.
  49668. */
  49669. set: function (value) {
  49670. this._shadowFrustumSize = value;
  49671. this.forceProjectionMatrixCompute();
  49672. },
  49673. enumerable: true,
  49674. configurable: true
  49675. });
  49676. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  49677. /**
  49678. * Gets the shadow projection scale against the optimal computed one.
  49679. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49680. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49681. */
  49682. get: function () {
  49683. return this._shadowOrthoScale;
  49684. },
  49685. /**
  49686. * Sets the shadow projection scale against the optimal computed one.
  49687. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49688. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49689. */
  49690. set: function (value) {
  49691. this._shadowOrthoScale = value;
  49692. this.forceProjectionMatrixCompute();
  49693. },
  49694. enumerable: true,
  49695. configurable: true
  49696. });
  49697. /**
  49698. * Returns the string "DirectionalLight".
  49699. * @return The class name
  49700. */
  49701. DirectionalLight.prototype.getClassName = function () {
  49702. return "DirectionalLight";
  49703. };
  49704. /**
  49705. * Returns the integer 1.
  49706. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49707. */
  49708. DirectionalLight.prototype.getTypeID = function () {
  49709. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  49710. };
  49711. /**
  49712. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  49713. * Returns the DirectionalLight Shadow projection matrix.
  49714. */
  49715. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49716. if (this.shadowFrustumSize > 0) {
  49717. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  49718. }
  49719. else {
  49720. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49721. }
  49722. };
  49723. /**
  49724. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  49725. * Returns the DirectionalLight Shadow projection matrix.
  49726. */
  49727. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  49728. var activeCamera = this.getScene().activeCamera;
  49729. if (!activeCamera) {
  49730. return;
  49731. }
  49732. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  49733. };
  49734. /**
  49735. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  49736. * Returns the DirectionalLight Shadow projection matrix.
  49737. */
  49738. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49739. var activeCamera = this.getScene().activeCamera;
  49740. if (!activeCamera) {
  49741. return;
  49742. }
  49743. // Check extends
  49744. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  49745. var tempVector3 = BABYLON.Vector3.Zero();
  49746. this._orthoLeft = Number.MAX_VALUE;
  49747. this._orthoRight = Number.MIN_VALUE;
  49748. this._orthoTop = Number.MIN_VALUE;
  49749. this._orthoBottom = Number.MAX_VALUE;
  49750. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  49751. var mesh = renderList[meshIndex];
  49752. if (!mesh) {
  49753. continue;
  49754. }
  49755. var boundingInfo = mesh.getBoundingInfo();
  49756. var boundingBox = boundingInfo.boundingBox;
  49757. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  49758. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  49759. if (tempVector3.x < this._orthoLeft)
  49760. this._orthoLeft = tempVector3.x;
  49761. if (tempVector3.y < this._orthoBottom)
  49762. this._orthoBottom = tempVector3.y;
  49763. if (tempVector3.x > this._orthoRight)
  49764. this._orthoRight = tempVector3.x;
  49765. if (tempVector3.y > this._orthoTop)
  49766. this._orthoTop = tempVector3.y;
  49767. }
  49768. }
  49769. }
  49770. var xOffset = this._orthoRight - this._orthoLeft;
  49771. var yOffset = this._orthoTop - this._orthoBottom;
  49772. 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);
  49773. };
  49774. DirectionalLight.prototype._buildUniformLayout = function () {
  49775. this._uniformBuffer.addUniform("vLightData", 4);
  49776. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49777. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49778. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49779. this._uniformBuffer.addUniform("depthValues", 2);
  49780. this._uniformBuffer.create();
  49781. };
  49782. /**
  49783. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  49784. * @param effect The effect to update
  49785. * @param lightIndex The index of the light in the effect to update
  49786. * @returns The directional light
  49787. */
  49788. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  49789. if (this.computeTransformedInformation()) {
  49790. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  49791. return this;
  49792. }
  49793. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  49794. return this;
  49795. };
  49796. /**
  49797. * Gets the minZ used for shadow according to both the scene and the light.
  49798. *
  49799. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49800. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49801. * @param activeCamera The camera we are returning the min for
  49802. * @returns the depth min z
  49803. */
  49804. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  49805. return 1;
  49806. };
  49807. /**
  49808. * Gets the maxZ used for shadow according to both the scene and the light.
  49809. *
  49810. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49811. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49812. * @param activeCamera The camera we are returning the max for
  49813. * @returns the depth max z
  49814. */
  49815. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  49816. return 1;
  49817. };
  49818. __decorate([
  49819. BABYLON.serialize()
  49820. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  49821. __decorate([
  49822. BABYLON.serialize()
  49823. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  49824. __decorate([
  49825. BABYLON.serialize()
  49826. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  49827. return DirectionalLight;
  49828. }(BABYLON.ShadowLight));
  49829. BABYLON.DirectionalLight = DirectionalLight;
  49830. })(BABYLON || (BABYLON = {}));
  49831. //# sourceMappingURL=babylon.directionalLight.js.map
  49832. var BABYLON;
  49833. (function (BABYLON) {
  49834. /**
  49835. * A spot light is defined by a position, a direction, an angle, and an exponent.
  49836. * These values define a cone of light starting from the position, emitting toward the direction.
  49837. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  49838. * and the exponent defines the speed of the decay of the light with distance (reach).
  49839. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49840. */
  49841. var SpotLight = /** @class */ (function (_super) {
  49842. __extends(SpotLight, _super);
  49843. /**
  49844. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  49845. * It can cast shadows.
  49846. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49847. * @param name The light friendly name
  49848. * @param position The position of the spot light in the scene
  49849. * @param direction The direction of the light in the scene
  49850. * @param angle The cone angle of the light in Radians
  49851. * @param exponent The light decay speed with the distance from the emission spot
  49852. * @param scene The scene the lights belongs to
  49853. */
  49854. function SpotLight(name, position, direction, angle, exponent, scene) {
  49855. var _this = _super.call(this, name, scene) || this;
  49856. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  49857. _this._projectionTextureLightNear = 1e-6;
  49858. _this._projectionTextureLightFar = 1000.0;
  49859. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  49860. _this._projectionTextureViewLightDirty = true;
  49861. _this._projectionTextureProjectionLightDirty = true;
  49862. _this._projectionTextureDirty = true;
  49863. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  49864. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  49865. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  49866. _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);
  49867. _this.position = position;
  49868. _this.direction = direction;
  49869. _this.angle = angle;
  49870. _this.exponent = exponent;
  49871. return _this;
  49872. }
  49873. Object.defineProperty(SpotLight.prototype, "angle", {
  49874. /**
  49875. * Gets the cone angle of the spot light in Radians.
  49876. */
  49877. get: function () {
  49878. return this._angle;
  49879. },
  49880. /**
  49881. * Sets the cone angle of the spot light in Radians.
  49882. */
  49883. set: function (value) {
  49884. this._angle = value;
  49885. this._projectionTextureProjectionLightDirty = true;
  49886. this.forceProjectionMatrixCompute();
  49887. },
  49888. enumerable: true,
  49889. configurable: true
  49890. });
  49891. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  49892. /**
  49893. * Allows scaling the angle of the light for shadow generation only.
  49894. */
  49895. get: function () {
  49896. return this._shadowAngleScale;
  49897. },
  49898. /**
  49899. * Allows scaling the angle of the light for shadow generation only.
  49900. */
  49901. set: function (value) {
  49902. this._shadowAngleScale = value;
  49903. this.forceProjectionMatrixCompute();
  49904. },
  49905. enumerable: true,
  49906. configurable: true
  49907. });
  49908. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  49909. /**
  49910. * Allows reading the projecton texture
  49911. */
  49912. get: function () {
  49913. return this._projectionTextureMatrix;
  49914. },
  49915. enumerable: true,
  49916. configurable: true
  49917. });
  49918. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  49919. /**
  49920. * Gets the near clip of the Spotlight for texture projection.
  49921. */
  49922. get: function () {
  49923. return this._projectionTextureLightNear;
  49924. },
  49925. /**
  49926. * Sets the near clip of the Spotlight for texture projection.
  49927. */
  49928. set: function (value) {
  49929. this._projectionTextureLightNear = value;
  49930. this._projectionTextureProjectionLightDirty = true;
  49931. },
  49932. enumerable: true,
  49933. configurable: true
  49934. });
  49935. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  49936. /**
  49937. * Gets the far clip of the Spotlight for texture projection.
  49938. */
  49939. get: function () {
  49940. return this._projectionTextureLightFar;
  49941. },
  49942. /**
  49943. * Sets the far clip of the Spotlight for texture projection.
  49944. */
  49945. set: function (value) {
  49946. this._projectionTextureLightFar = value;
  49947. this._projectionTextureProjectionLightDirty = true;
  49948. },
  49949. enumerable: true,
  49950. configurable: true
  49951. });
  49952. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  49953. /**
  49954. * Gets the Up vector of the Spotlight for texture projection.
  49955. */
  49956. get: function () {
  49957. return this._projectionTextureUpDirection;
  49958. },
  49959. /**
  49960. * Sets the Up vector of the Spotlight for texture projection.
  49961. */
  49962. set: function (value) {
  49963. this._projectionTextureUpDirection = value;
  49964. this._projectionTextureProjectionLightDirty = true;
  49965. },
  49966. enumerable: true,
  49967. configurable: true
  49968. });
  49969. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  49970. /**
  49971. * Gets the projection texture of the light.
  49972. */
  49973. get: function () {
  49974. return this._projectionTexture;
  49975. },
  49976. /**
  49977. * Sets the projection texture of the light.
  49978. */
  49979. set: function (value) {
  49980. this._projectionTexture = value;
  49981. this._projectionTextureDirty = true;
  49982. },
  49983. enumerable: true,
  49984. configurable: true
  49985. });
  49986. /**
  49987. * Returns the string "SpotLight".
  49988. * @returns the class name
  49989. */
  49990. SpotLight.prototype.getClassName = function () {
  49991. return "SpotLight";
  49992. };
  49993. /**
  49994. * Returns the integer 2.
  49995. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49996. */
  49997. SpotLight.prototype.getTypeID = function () {
  49998. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  49999. };
  50000. /**
  50001. * Overrides the direction setter to recompute the projection texture view light Matrix.
  50002. */
  50003. SpotLight.prototype._setDirection = function (value) {
  50004. _super.prototype._setDirection.call(this, value);
  50005. this._projectionTextureViewLightDirty = true;
  50006. };
  50007. /**
  50008. * Overrides the position setter to recompute the projection texture view light Matrix.
  50009. */
  50010. SpotLight.prototype._setPosition = function (value) {
  50011. _super.prototype._setPosition.call(this, value);
  50012. this._projectionTextureViewLightDirty = true;
  50013. };
  50014. /**
  50015. * 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.
  50016. * Returns the SpotLight.
  50017. */
  50018. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50019. var activeCamera = this.getScene().activeCamera;
  50020. if (!activeCamera) {
  50021. return;
  50022. }
  50023. this._shadowAngleScale = this._shadowAngleScale || 1;
  50024. var angle = this._shadowAngleScale * this._angle;
  50025. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  50026. };
  50027. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  50028. this._projectionTextureViewLightDirty = false;
  50029. this._projectionTextureDirty = true;
  50030. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  50031. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  50032. };
  50033. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  50034. this._projectionTextureProjectionLightDirty = false;
  50035. this._projectionTextureDirty = true;
  50036. var light_far = this.projectionTextureLightFar;
  50037. var light_near = this.projectionTextureLightNear;
  50038. var P = light_far / (light_far - light_near);
  50039. var Q = -P * light_near;
  50040. var S = 1.0 / Math.tan(this._angle / 2.0);
  50041. var A = 1.0;
  50042. 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);
  50043. };
  50044. /**
  50045. * Main function for light texture projection matrix computing.
  50046. */
  50047. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  50048. this._projectionTextureDirty = false;
  50049. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  50050. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  50051. };
  50052. SpotLight.prototype._buildUniformLayout = function () {
  50053. this._uniformBuffer.addUniform("vLightData", 4);
  50054. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  50055. this._uniformBuffer.addUniform("vLightSpecular", 3);
  50056. this._uniformBuffer.addUniform("vLightDirection", 3);
  50057. this._uniformBuffer.addUniform("shadowsInfo", 3);
  50058. this._uniformBuffer.addUniform("depthValues", 2);
  50059. this._uniformBuffer.create();
  50060. };
  50061. /**
  50062. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  50063. * @param effect The effect to update
  50064. * @param lightIndex The index of the light in the effect to update
  50065. * @returns The spot light
  50066. */
  50067. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  50068. var normalizeDirection;
  50069. if (this.computeTransformedInformation()) {
  50070. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  50071. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  50072. }
  50073. else {
  50074. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  50075. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  50076. }
  50077. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  50078. if (this.projectionTexture && this.projectionTexture.isReady()) {
  50079. if (this._projectionTextureViewLightDirty) {
  50080. this._computeProjectionTextureViewLightMatrix();
  50081. }
  50082. if (this._projectionTextureProjectionLightDirty) {
  50083. this._computeProjectionTextureProjectionLightMatrix();
  50084. }
  50085. if (this._projectionTextureDirty) {
  50086. this._computeProjectionTextureMatrix();
  50087. }
  50088. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  50089. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  50090. }
  50091. return this;
  50092. };
  50093. /**
  50094. * Disposes the light and the associated resources.
  50095. */
  50096. SpotLight.prototype.dispose = function () {
  50097. _super.prototype.dispose.call(this);
  50098. if (this._projectionTexture) {
  50099. this._projectionTexture.dispose();
  50100. }
  50101. };
  50102. __decorate([
  50103. BABYLON.serialize()
  50104. ], SpotLight.prototype, "angle", null);
  50105. __decorate([
  50106. BABYLON.serialize()
  50107. ], SpotLight.prototype, "shadowAngleScale", null);
  50108. __decorate([
  50109. BABYLON.serialize()
  50110. ], SpotLight.prototype, "exponent", void 0);
  50111. __decorate([
  50112. BABYLON.serialize()
  50113. ], SpotLight.prototype, "projectionTextureLightNear", null);
  50114. __decorate([
  50115. BABYLON.serialize()
  50116. ], SpotLight.prototype, "projectionTextureLightFar", null);
  50117. __decorate([
  50118. BABYLON.serialize()
  50119. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  50120. __decorate([
  50121. BABYLON.serializeAsTexture("projectedLightTexture")
  50122. ], SpotLight.prototype, "_projectionTexture", void 0);
  50123. return SpotLight;
  50124. }(BABYLON.ShadowLight));
  50125. BABYLON.SpotLight = SpotLight;
  50126. })(BABYLON || (BABYLON = {}));
  50127. //# sourceMappingURL=babylon.spotLight.js.map
  50128. var BABYLON;
  50129. (function (BABYLON) {
  50130. /**
  50131. * Class used to override all child animations of a given target
  50132. */
  50133. var AnimationPropertiesOverride = /** @class */ (function () {
  50134. function AnimationPropertiesOverride() {
  50135. /**
  50136. * Gets or sets a value indicating if animation blending must be used
  50137. */
  50138. this.enableBlending = false;
  50139. /**
  50140. * Gets or sets the blending speed to use when enableBlending is true
  50141. */
  50142. this.blendingSpeed = 0.01;
  50143. /**
  50144. * Gets or sets the default loop mode to use
  50145. */
  50146. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  50147. }
  50148. return AnimationPropertiesOverride;
  50149. }());
  50150. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  50151. })(BABYLON || (BABYLON = {}));
  50152. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  50153. var BABYLON;
  50154. (function (BABYLON) {
  50155. /**
  50156. * Represents the range of an animation
  50157. */
  50158. var AnimationRange = /** @class */ (function () {
  50159. /**
  50160. * Initializes the range of an animation
  50161. * @param name The name of the animation range
  50162. * @param from The starting frame of the animation
  50163. * @param to The ending frame of the animation
  50164. */
  50165. function AnimationRange(
  50166. /**The name of the animation range**/
  50167. name,
  50168. /**The starting frame of the animation */
  50169. from,
  50170. /**The ending frame of the animation*/
  50171. to) {
  50172. this.name = name;
  50173. this.from = from;
  50174. this.to = to;
  50175. }
  50176. /**
  50177. * Makes a copy of the animation range
  50178. * @returns A copy of the animation range
  50179. */
  50180. AnimationRange.prototype.clone = function () {
  50181. return new AnimationRange(this.name, this.from, this.to);
  50182. };
  50183. return AnimationRange;
  50184. }());
  50185. BABYLON.AnimationRange = AnimationRange;
  50186. /**
  50187. * Composed of a frame, and an action function
  50188. */
  50189. var AnimationEvent = /** @class */ (function () {
  50190. /**
  50191. * Initializes the animation event
  50192. * @param frame The frame for which the event is triggered
  50193. * @param action The event to perform when triggered
  50194. * @param onlyOnce Specifies if the event should be triggered only once
  50195. */
  50196. function AnimationEvent(
  50197. /** The frame for which the event is triggered **/
  50198. frame,
  50199. /** The event to perform when triggered **/
  50200. action,
  50201. /** Specifies if the event should be triggered only once**/
  50202. onlyOnce) {
  50203. this.frame = frame;
  50204. this.action = action;
  50205. this.onlyOnce = onlyOnce;
  50206. /**
  50207. * Specifies if the animation event is done
  50208. */
  50209. this.isDone = false;
  50210. }
  50211. return AnimationEvent;
  50212. }());
  50213. BABYLON.AnimationEvent = AnimationEvent;
  50214. /**
  50215. * A cursor which tracks a point on a path
  50216. */
  50217. var PathCursor = /** @class */ (function () {
  50218. /**
  50219. * Initializes the path cursor
  50220. * @param path The path to track
  50221. */
  50222. function PathCursor(path) {
  50223. this.path = path;
  50224. /**
  50225. * Stores path cursor callbacks for when an onchange event is triggered
  50226. */
  50227. this._onchange = new Array();
  50228. /**
  50229. * The value of the path cursor
  50230. */
  50231. this.value = 0;
  50232. /**
  50233. * The animation array of the path cursor
  50234. */
  50235. this.animations = new Array();
  50236. }
  50237. /**
  50238. * Gets the cursor point on the path
  50239. * @returns A point on the path cursor at the cursor location
  50240. */
  50241. PathCursor.prototype.getPoint = function () {
  50242. var point = this.path.getPointAtLengthPosition(this.value);
  50243. return new BABYLON.Vector3(point.x, 0, point.y);
  50244. };
  50245. /**
  50246. * Moves the cursor ahead by the step amount
  50247. * @param step The amount to move the cursor forward
  50248. * @returns This path cursor
  50249. */
  50250. PathCursor.prototype.moveAhead = function (step) {
  50251. if (step === void 0) { step = 0.002; }
  50252. this.move(step);
  50253. return this;
  50254. };
  50255. /**
  50256. * Moves the cursor behind by the step amount
  50257. * @param step The amount to move the cursor back
  50258. * @returns This path cursor
  50259. */
  50260. PathCursor.prototype.moveBack = function (step) {
  50261. if (step === void 0) { step = 0.002; }
  50262. this.move(-step);
  50263. return this;
  50264. };
  50265. /**
  50266. * Moves the cursor by the step amount
  50267. * If the step amount is greater than one, an exception is thrown
  50268. * @param step The amount to move the cursor
  50269. * @returns This path cursor
  50270. */
  50271. PathCursor.prototype.move = function (step) {
  50272. if (Math.abs(step) > 1) {
  50273. throw "step size should be less than 1.";
  50274. }
  50275. this.value += step;
  50276. this.ensureLimits();
  50277. this.raiseOnChange();
  50278. return this;
  50279. };
  50280. /**
  50281. * Ensures that the value is limited between zero and one
  50282. * @returns This path cursor
  50283. */
  50284. PathCursor.prototype.ensureLimits = function () {
  50285. while (this.value > 1) {
  50286. this.value -= 1;
  50287. }
  50288. while (this.value < 0) {
  50289. this.value += 1;
  50290. }
  50291. return this;
  50292. };
  50293. /**
  50294. * Runs onchange callbacks on change (used by the animation engine)
  50295. * @returns This path cursor
  50296. */
  50297. PathCursor.prototype.raiseOnChange = function () {
  50298. var _this = this;
  50299. this._onchange.forEach(function (f) { return f(_this); });
  50300. return this;
  50301. };
  50302. /**
  50303. * Executes a function on change
  50304. * @param f A path cursor onchange callback
  50305. * @returns This path cursor
  50306. */
  50307. PathCursor.prototype.onchange = function (f) {
  50308. this._onchange.push(f);
  50309. return this;
  50310. };
  50311. return PathCursor;
  50312. }());
  50313. BABYLON.PathCursor = PathCursor;
  50314. /**
  50315. * Enum for the animation key frame interpolation type
  50316. */
  50317. var AnimationKeyInterpolation;
  50318. (function (AnimationKeyInterpolation) {
  50319. /**
  50320. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  50321. */
  50322. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  50323. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  50324. /**
  50325. * Class used to store any kind of animation
  50326. */
  50327. var Animation = /** @class */ (function () {
  50328. /**
  50329. * Initializes the animation
  50330. * @param name Name of the animation
  50331. * @param targetProperty Property to animate
  50332. * @param framePerSecond The frames per second of the animation
  50333. * @param dataType The data type of the animation
  50334. * @param loopMode The loop mode of the animation
  50335. * @param enableBlendings Specifies if blending should be enabled
  50336. */
  50337. function Animation(
  50338. /**Name of the animation */
  50339. name,
  50340. /**Property to animate */
  50341. targetProperty,
  50342. /**The frames per second of the animation */
  50343. framePerSecond,
  50344. /**The data type of the animation */
  50345. dataType,
  50346. /**The loop mode of the animation */
  50347. loopMode,
  50348. /**Specifies if blending should be enabled */
  50349. enableBlending) {
  50350. this.name = name;
  50351. this.targetProperty = targetProperty;
  50352. this.framePerSecond = framePerSecond;
  50353. this.dataType = dataType;
  50354. this.loopMode = loopMode;
  50355. this.enableBlending = enableBlending;
  50356. /**
  50357. * @hidden Internal use only
  50358. */
  50359. this._runtimeAnimations = new Array();
  50360. /**
  50361. * The set of event that will be linked to this animation
  50362. */
  50363. this._events = new Array();
  50364. /**
  50365. * Stores the blending speed of the animation
  50366. */
  50367. this.blendingSpeed = 0.01;
  50368. /**
  50369. * Stores the animation ranges for the animation
  50370. */
  50371. this._ranges = {};
  50372. this.targetPropertyPath = targetProperty.split(".");
  50373. this.dataType = dataType;
  50374. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  50375. }
  50376. /**
  50377. * @hidden Internal use
  50378. */
  50379. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  50380. var dataType = undefined;
  50381. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  50382. dataType = Animation.ANIMATIONTYPE_FLOAT;
  50383. }
  50384. else if (from instanceof BABYLON.Quaternion) {
  50385. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  50386. }
  50387. else if (from instanceof BABYLON.Vector3) {
  50388. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  50389. }
  50390. else if (from instanceof BABYLON.Vector2) {
  50391. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  50392. }
  50393. else if (from instanceof BABYLON.Color3) {
  50394. dataType = Animation.ANIMATIONTYPE_COLOR3;
  50395. }
  50396. else if (from instanceof BABYLON.Size) {
  50397. dataType = Animation.ANIMATIONTYPE_SIZE;
  50398. }
  50399. if (dataType == undefined) {
  50400. return null;
  50401. }
  50402. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  50403. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  50404. animation.setKeys(keys);
  50405. if (easingFunction !== undefined) {
  50406. animation.setEasingFunction(easingFunction);
  50407. }
  50408. return animation;
  50409. };
  50410. /**
  50411. * Sets up an animation
  50412. * @param property The property to animate
  50413. * @param animationType The animation type to apply
  50414. * @param framePerSecond The frames per second of the animation
  50415. * @param easingFunction The easing function used in the animation
  50416. * @returns The created animation
  50417. */
  50418. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  50419. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  50420. animation.setEasingFunction(easingFunction);
  50421. return animation;
  50422. };
  50423. /**
  50424. * Create and start an animation on a node
  50425. * @param name defines the name of the global animation that will be run on all nodes
  50426. * @param node defines the root node where the animation will take place
  50427. * @param targetProperty defines property to animate
  50428. * @param framePerSecond defines the number of frame per second yo use
  50429. * @param totalFrame defines the number of frames in total
  50430. * @param from defines the initial value
  50431. * @param to defines the final value
  50432. * @param loopMode defines which loop mode you want to use (off by default)
  50433. * @param easingFunction defines the easing function to use (linear by default)
  50434. * @param onAnimationEnd defines the callback to call when animation end
  50435. * @returns the animatable created for this animation
  50436. */
  50437. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50438. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50439. if (!animation) {
  50440. return null;
  50441. }
  50442. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50443. };
  50444. /**
  50445. * Create and start an animation on a node and its descendants
  50446. * @param name defines the name of the global animation that will be run on all nodes
  50447. * @param node defines the root node where the animation will take place
  50448. * @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
  50449. * @param targetProperty defines property to animate
  50450. * @param framePerSecond defines the number of frame per second to use
  50451. * @param totalFrame defines the number of frames in total
  50452. * @param from defines the initial value
  50453. * @param to defines the final value
  50454. * @param loopMode defines which loop mode you want to use (off by default)
  50455. * @param easingFunction defines the easing function to use (linear by default)
  50456. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  50457. * @returns the list of animatables created for all nodes
  50458. * @example https://www.babylonjs-playground.com/#MH0VLI
  50459. */
  50460. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50461. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50462. if (!animation) {
  50463. return null;
  50464. }
  50465. var scene = node.getScene();
  50466. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50467. };
  50468. /**
  50469. * Creates a new animation, merges it with the existing animations and starts it
  50470. * @param name Name of the animation
  50471. * @param node Node which contains the scene that begins the animations
  50472. * @param targetProperty Specifies which property to animate
  50473. * @param framePerSecond The frames per second of the animation
  50474. * @param totalFrame The total number of frames
  50475. * @param from The frame at the beginning of the animation
  50476. * @param to The frame at the end of the animation
  50477. * @param loopMode Specifies the loop mode of the animation
  50478. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  50479. * @param onAnimationEnd Callback to run once the animation is complete
  50480. * @returns Nullable animation
  50481. */
  50482. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50483. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50484. if (!animation) {
  50485. return null;
  50486. }
  50487. node.animations.push(animation);
  50488. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50489. };
  50490. /**
  50491. * Transition property of the Camera to the target Value
  50492. * @param property The property to transition
  50493. * @param targetValue The target Value of the property
  50494. * @param host The object where the property to animate belongs
  50495. * @param scene Scene used to run the animation
  50496. * @param frameRate Framerate (in frame/s) to use
  50497. * @param transition The transition type we want to use
  50498. * @param duration The duration of the animation, in milliseconds
  50499. * @param onAnimationEnd Callback trigger at the end of the animation
  50500. * @returns Nullable animation
  50501. */
  50502. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  50503. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  50504. if (duration <= 0) {
  50505. host[property] = targetValue;
  50506. if (onAnimationEnd) {
  50507. onAnimationEnd();
  50508. }
  50509. return null;
  50510. }
  50511. var endFrame = frameRate * (duration / 1000);
  50512. transition.setKeys([{
  50513. frame: 0,
  50514. value: host[property].clone ? host[property].clone() : host[property]
  50515. },
  50516. {
  50517. frame: endFrame,
  50518. value: targetValue
  50519. }]);
  50520. if (!host.animations) {
  50521. host.animations = [];
  50522. }
  50523. host.animations.push(transition);
  50524. var animation = scene.beginAnimation(host, 0, endFrame, false);
  50525. animation.onAnimationEnd = onAnimationEnd;
  50526. return animation;
  50527. };
  50528. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  50529. /**
  50530. * Return the array of runtime animations currently using this animation
  50531. */
  50532. get: function () {
  50533. return this._runtimeAnimations;
  50534. },
  50535. enumerable: true,
  50536. configurable: true
  50537. });
  50538. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  50539. /**
  50540. * Specifies if any of the runtime animations are currently running
  50541. */
  50542. get: function () {
  50543. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  50544. var runtimeAnimation = _a[_i];
  50545. if (!runtimeAnimation.isStopped) {
  50546. return true;
  50547. }
  50548. }
  50549. return false;
  50550. },
  50551. enumerable: true,
  50552. configurable: true
  50553. });
  50554. // Methods
  50555. /**
  50556. * Converts the animation to a string
  50557. * @param fullDetails support for multiple levels of logging within scene loading
  50558. * @returns String form of the animation
  50559. */
  50560. Animation.prototype.toString = function (fullDetails) {
  50561. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  50562. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  50563. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  50564. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  50565. if (fullDetails) {
  50566. ret += ", Ranges: {";
  50567. var first = true;
  50568. for (var name in this._ranges) {
  50569. if (first) {
  50570. ret += ", ";
  50571. first = false;
  50572. }
  50573. ret += name;
  50574. }
  50575. ret += "}";
  50576. }
  50577. return ret;
  50578. };
  50579. /**
  50580. * Add an event to this animation
  50581. * @param event Event to add
  50582. */
  50583. Animation.prototype.addEvent = function (event) {
  50584. this._events.push(event);
  50585. };
  50586. /**
  50587. * Remove all events found at the given frame
  50588. * @param frame The frame to remove events from
  50589. */
  50590. Animation.prototype.removeEvents = function (frame) {
  50591. for (var index = 0; index < this._events.length; index++) {
  50592. if (this._events[index].frame === frame) {
  50593. this._events.splice(index, 1);
  50594. index--;
  50595. }
  50596. }
  50597. };
  50598. /**
  50599. * Retrieves all the events from the animation
  50600. * @returns Events from the animation
  50601. */
  50602. Animation.prototype.getEvents = function () {
  50603. return this._events;
  50604. };
  50605. /**
  50606. * Creates an animation range
  50607. * @param name Name of the animation range
  50608. * @param from Starting frame of the animation range
  50609. * @param to Ending frame of the animation
  50610. */
  50611. Animation.prototype.createRange = function (name, from, to) {
  50612. // check name not already in use; could happen for bones after serialized
  50613. if (!this._ranges[name]) {
  50614. this._ranges[name] = new AnimationRange(name, from, to);
  50615. }
  50616. };
  50617. /**
  50618. * Deletes an animation range by name
  50619. * @param name Name of the animation range to delete
  50620. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  50621. */
  50622. Animation.prototype.deleteRange = function (name, deleteFrames) {
  50623. if (deleteFrames === void 0) { deleteFrames = true; }
  50624. var range = this._ranges[name];
  50625. if (!range) {
  50626. return;
  50627. }
  50628. if (deleteFrames) {
  50629. var from = range.from;
  50630. var to = range.to;
  50631. // this loop MUST go high to low for multiple splices to work
  50632. for (var key = this._keys.length - 1; key >= 0; key--) {
  50633. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  50634. this._keys.splice(key, 1);
  50635. }
  50636. }
  50637. }
  50638. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  50639. };
  50640. /**
  50641. * Gets the animation range by name, or null if not defined
  50642. * @param name Name of the animation range
  50643. * @returns Nullable animation range
  50644. */
  50645. Animation.prototype.getRange = function (name) {
  50646. return this._ranges[name];
  50647. };
  50648. /**
  50649. * Gets the key frames from the animation
  50650. * @returns The key frames of the animation
  50651. */
  50652. Animation.prototype.getKeys = function () {
  50653. return this._keys;
  50654. };
  50655. /**
  50656. * Gets the highest frame rate of the animation
  50657. * @returns Highest frame rate of the animation
  50658. */
  50659. Animation.prototype.getHighestFrame = function () {
  50660. var ret = 0;
  50661. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  50662. if (ret < this._keys[key].frame) {
  50663. ret = this._keys[key].frame;
  50664. }
  50665. }
  50666. return ret;
  50667. };
  50668. /**
  50669. * Gets the easing function of the animation
  50670. * @returns Easing function of the animation
  50671. */
  50672. Animation.prototype.getEasingFunction = function () {
  50673. return this._easingFunction;
  50674. };
  50675. /**
  50676. * Sets the easing function of the animation
  50677. * @param easingFunction A custom mathematical formula for animation
  50678. */
  50679. Animation.prototype.setEasingFunction = function (easingFunction) {
  50680. this._easingFunction = easingFunction;
  50681. };
  50682. /**
  50683. * Interpolates a scalar linearly
  50684. * @param startValue Start value of the animation curve
  50685. * @param endValue End value of the animation curve
  50686. * @param gradient Scalar amount to interpolate
  50687. * @returns Interpolated scalar value
  50688. */
  50689. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  50690. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  50691. };
  50692. /**
  50693. * Interpolates a scalar cubically
  50694. * @param startValue Start value of the animation curve
  50695. * @param outTangent End tangent of the animation
  50696. * @param endValue End value of the animation curve
  50697. * @param inTangent Start tangent of the animation curve
  50698. * @param gradient Scalar amount to interpolate
  50699. * @returns Interpolated scalar value
  50700. */
  50701. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50702. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50703. };
  50704. /**
  50705. * Interpolates a quaternion using a spherical linear interpolation
  50706. * @param startValue Start value of the animation curve
  50707. * @param endValue End value of the animation curve
  50708. * @param gradient Scalar amount to interpolate
  50709. * @returns Interpolated quaternion value
  50710. */
  50711. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  50712. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  50713. };
  50714. /**
  50715. * Interpolates a quaternion cubically
  50716. * @param startValue Start value of the animation curve
  50717. * @param outTangent End tangent of the animation curve
  50718. * @param endValue End value of the animation curve
  50719. * @param inTangent Start tangent of the animation curve
  50720. * @param gradient Scalar amount to interpolate
  50721. * @returns Interpolated quaternion value
  50722. */
  50723. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50724. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  50725. };
  50726. /**
  50727. * Interpolates a Vector3 linearl
  50728. * @param startValue Start value of the animation curve
  50729. * @param endValue End value of the animation curve
  50730. * @param gradient Scalar amount to interpolate
  50731. * @returns Interpolated scalar value
  50732. */
  50733. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  50734. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  50735. };
  50736. /**
  50737. * Interpolates a Vector3 cubically
  50738. * @param startValue Start value of the animation curve
  50739. * @param outTangent End tangent of the animation
  50740. * @param endValue End value of the animation curve
  50741. * @param inTangent Start tangent of the animation curve
  50742. * @param gradient Scalar amount to interpolate
  50743. * @returns InterpolatedVector3 value
  50744. */
  50745. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50746. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50747. };
  50748. /**
  50749. * Interpolates a Vector2 linearly
  50750. * @param startValue Start value of the animation curve
  50751. * @param endValue End value of the animation curve
  50752. * @param gradient Scalar amount to interpolate
  50753. * @returns Interpolated Vector2 value
  50754. */
  50755. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  50756. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  50757. };
  50758. /**
  50759. * Interpolates a Vector2 cubically
  50760. * @param startValue Start value of the animation curve
  50761. * @param outTangent End tangent of the animation
  50762. * @param endValue End value of the animation curve
  50763. * @param inTangent Start tangent of the animation curve
  50764. * @param gradient Scalar amount to interpolate
  50765. * @returns Interpolated Vector2 value
  50766. */
  50767. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50768. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50769. };
  50770. /**
  50771. * Interpolates a size linearly
  50772. * @param startValue Start value of the animation curve
  50773. * @param endValue End value of the animation curve
  50774. * @param gradient Scalar amount to interpolate
  50775. * @returns Interpolated Size value
  50776. */
  50777. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  50778. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  50779. };
  50780. /**
  50781. * Interpolates a Color3 linearly
  50782. * @param startValue Start value of the animation curve
  50783. * @param endValue End value of the animation curve
  50784. * @param gradient Scalar amount to interpolate
  50785. * @returns Interpolated Color3 value
  50786. */
  50787. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  50788. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  50789. };
  50790. /**
  50791. * @hidden Internal use only
  50792. */
  50793. Animation.prototype._getKeyValue = function (value) {
  50794. if (typeof value === "function") {
  50795. return value();
  50796. }
  50797. return value;
  50798. };
  50799. /**
  50800. * @hidden Internal use only
  50801. */
  50802. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  50803. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  50804. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  50805. }
  50806. var keys = this.getKeys();
  50807. // Try to get a hash to find the right key
  50808. 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));
  50809. if (keys[startKeyIndex].frame >= currentFrame) {
  50810. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  50811. startKeyIndex--;
  50812. }
  50813. }
  50814. for (var key = startKeyIndex; key < keys.length; key++) {
  50815. var endKey = keys[key + 1];
  50816. if (endKey.frame >= currentFrame) {
  50817. var startKey = keys[key];
  50818. var startValue = this._getKeyValue(startKey.value);
  50819. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  50820. return startValue;
  50821. }
  50822. var endValue = this._getKeyValue(endKey.value);
  50823. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  50824. var frameDelta = endKey.frame - startKey.frame;
  50825. // gradient : percent of currentFrame between the frame inf and the frame sup
  50826. var gradient = (currentFrame - startKey.frame) / frameDelta;
  50827. // check for easingFunction and correction of gradient
  50828. var easingFunction = this.getEasingFunction();
  50829. if (easingFunction != null) {
  50830. gradient = easingFunction.ease(gradient);
  50831. }
  50832. switch (this.dataType) {
  50833. // Float
  50834. case Animation.ANIMATIONTYPE_FLOAT:
  50835. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  50836. switch (loopMode) {
  50837. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50838. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50839. return floatValue;
  50840. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50841. return offsetValue * repeatCount + floatValue;
  50842. }
  50843. break;
  50844. // Quaternion
  50845. case Animation.ANIMATIONTYPE_QUATERNION:
  50846. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  50847. switch (loopMode) {
  50848. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50849. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50850. return quatValue;
  50851. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50852. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  50853. }
  50854. return quatValue;
  50855. // Vector3
  50856. case Animation.ANIMATIONTYPE_VECTOR3:
  50857. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  50858. switch (loopMode) {
  50859. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50860. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50861. return vec3Value;
  50862. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50863. return vec3Value.add(offsetValue.scale(repeatCount));
  50864. }
  50865. // Vector2
  50866. case Animation.ANIMATIONTYPE_VECTOR2:
  50867. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  50868. switch (loopMode) {
  50869. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50870. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50871. return vec2Value;
  50872. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50873. return vec2Value.add(offsetValue.scale(repeatCount));
  50874. }
  50875. // Size
  50876. case Animation.ANIMATIONTYPE_SIZE:
  50877. switch (loopMode) {
  50878. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50879. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50880. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  50881. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50882. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50883. }
  50884. // Color3
  50885. case Animation.ANIMATIONTYPE_COLOR3:
  50886. switch (loopMode) {
  50887. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50888. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50889. return this.color3InterpolateFunction(startValue, endValue, gradient);
  50890. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50891. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50892. }
  50893. // Matrix
  50894. case Animation.ANIMATIONTYPE_MATRIX:
  50895. switch (loopMode) {
  50896. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50897. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50898. if (Animation.AllowMatricesInterpolation) {
  50899. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  50900. }
  50901. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50902. return startValue;
  50903. }
  50904. default:
  50905. break;
  50906. }
  50907. break;
  50908. }
  50909. }
  50910. return this._getKeyValue(keys[keys.length - 1].value);
  50911. };
  50912. /**
  50913. * Defines the function to use to interpolate matrices
  50914. * @param startValue defines the start matrix
  50915. * @param endValue defines the end matrix
  50916. * @param gradient defines the gradient between both matrices
  50917. * @param result defines an optional target matrix where to store the interpolation
  50918. * @returns the interpolated matrix
  50919. */
  50920. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  50921. if (Animation.AllowMatrixDecomposeForInterpolation) {
  50922. if (result) {
  50923. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  50924. return result;
  50925. }
  50926. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  50927. }
  50928. if (result) {
  50929. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  50930. return result;
  50931. }
  50932. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  50933. };
  50934. /**
  50935. * Makes a copy of the animation
  50936. * @returns Cloned animation
  50937. */
  50938. Animation.prototype.clone = function () {
  50939. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  50940. clone.enableBlending = this.enableBlending;
  50941. clone.blendingSpeed = this.blendingSpeed;
  50942. if (this._keys) {
  50943. clone.setKeys(this._keys);
  50944. }
  50945. if (this._ranges) {
  50946. clone._ranges = {};
  50947. for (var name in this._ranges) {
  50948. var range = this._ranges[name];
  50949. if (!range) {
  50950. continue;
  50951. }
  50952. clone._ranges[name] = range.clone();
  50953. }
  50954. }
  50955. return clone;
  50956. };
  50957. /**
  50958. * Sets the key frames of the animation
  50959. * @param values The animation key frames to set
  50960. */
  50961. Animation.prototype.setKeys = function (values) {
  50962. this._keys = values.slice(0);
  50963. };
  50964. /**
  50965. * Serializes the animation to an object
  50966. * @returns Serialized object
  50967. */
  50968. Animation.prototype.serialize = function () {
  50969. var serializationObject = {};
  50970. serializationObject.name = this.name;
  50971. serializationObject.property = this.targetProperty;
  50972. serializationObject.framePerSecond = this.framePerSecond;
  50973. serializationObject.dataType = this.dataType;
  50974. serializationObject.loopBehavior = this.loopMode;
  50975. serializationObject.enableBlending = this.enableBlending;
  50976. serializationObject.blendingSpeed = this.blendingSpeed;
  50977. var dataType = this.dataType;
  50978. serializationObject.keys = [];
  50979. var keys = this.getKeys();
  50980. for (var index = 0; index < keys.length; index++) {
  50981. var animationKey = keys[index];
  50982. var key = {};
  50983. key.frame = animationKey.frame;
  50984. switch (dataType) {
  50985. case Animation.ANIMATIONTYPE_FLOAT:
  50986. key.values = [animationKey.value];
  50987. break;
  50988. case Animation.ANIMATIONTYPE_QUATERNION:
  50989. case Animation.ANIMATIONTYPE_MATRIX:
  50990. case Animation.ANIMATIONTYPE_VECTOR3:
  50991. case Animation.ANIMATIONTYPE_COLOR3:
  50992. key.values = animationKey.value.asArray();
  50993. break;
  50994. }
  50995. serializationObject.keys.push(key);
  50996. }
  50997. serializationObject.ranges = [];
  50998. for (var name in this._ranges) {
  50999. var source = this._ranges[name];
  51000. if (!source) {
  51001. continue;
  51002. }
  51003. var range = {};
  51004. range.name = name;
  51005. range.from = source.from;
  51006. range.to = source.to;
  51007. serializationObject.ranges.push(range);
  51008. }
  51009. return serializationObject;
  51010. };
  51011. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  51012. /**
  51013. * Get the float animation type
  51014. */
  51015. get: function () {
  51016. return Animation._ANIMATIONTYPE_FLOAT;
  51017. },
  51018. enumerable: true,
  51019. configurable: true
  51020. });
  51021. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  51022. /**
  51023. * Get the Vector3 animation type
  51024. */
  51025. get: function () {
  51026. return Animation._ANIMATIONTYPE_VECTOR3;
  51027. },
  51028. enumerable: true,
  51029. configurable: true
  51030. });
  51031. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  51032. /**
  51033. * Get the Vectpr2 animation type
  51034. */
  51035. get: function () {
  51036. return Animation._ANIMATIONTYPE_VECTOR2;
  51037. },
  51038. enumerable: true,
  51039. configurable: true
  51040. });
  51041. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  51042. /**
  51043. * Get the Size animation type
  51044. */
  51045. get: function () {
  51046. return Animation._ANIMATIONTYPE_SIZE;
  51047. },
  51048. enumerable: true,
  51049. configurable: true
  51050. });
  51051. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  51052. /**
  51053. * Get the Quaternion animation type
  51054. */
  51055. get: function () {
  51056. return Animation._ANIMATIONTYPE_QUATERNION;
  51057. },
  51058. enumerable: true,
  51059. configurable: true
  51060. });
  51061. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  51062. /**
  51063. * Get the Matrix animation type
  51064. */
  51065. get: function () {
  51066. return Animation._ANIMATIONTYPE_MATRIX;
  51067. },
  51068. enumerable: true,
  51069. configurable: true
  51070. });
  51071. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  51072. /**
  51073. * Get the Color3 animation type
  51074. */
  51075. get: function () {
  51076. return Animation._ANIMATIONTYPE_COLOR3;
  51077. },
  51078. enumerable: true,
  51079. configurable: true
  51080. });
  51081. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  51082. /**
  51083. * Get the Relative Loop Mode
  51084. */
  51085. get: function () {
  51086. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  51087. },
  51088. enumerable: true,
  51089. configurable: true
  51090. });
  51091. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  51092. /**
  51093. * Get the Cycle Loop Mode
  51094. */
  51095. get: function () {
  51096. return Animation._ANIMATIONLOOPMODE_CYCLE;
  51097. },
  51098. enumerable: true,
  51099. configurable: true
  51100. });
  51101. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  51102. /**
  51103. * Get the Constant Loop Mode
  51104. */
  51105. get: function () {
  51106. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  51107. },
  51108. enumerable: true,
  51109. configurable: true
  51110. });
  51111. /** @hidden */
  51112. Animation._UniversalLerp = function (left, right, amount) {
  51113. var constructor = left.constructor;
  51114. if (constructor.Lerp) { // Lerp supported
  51115. return constructor.Lerp(left, right, amount);
  51116. }
  51117. else if (constructor.Slerp) { // Slerp supported
  51118. return constructor.Slerp(left, right, amount);
  51119. }
  51120. else if (left.toFixed) { // Number
  51121. return left * (1.0 - amount) + amount * right;
  51122. }
  51123. else { // Blending not supported
  51124. return right;
  51125. }
  51126. };
  51127. /**
  51128. * Parses an animation object and creates an animation
  51129. * @param parsedAnimation Parsed animation object
  51130. * @returns Animation object
  51131. */
  51132. Animation.Parse = function (parsedAnimation) {
  51133. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  51134. var dataType = parsedAnimation.dataType;
  51135. var keys = [];
  51136. var data;
  51137. var index;
  51138. if (parsedAnimation.enableBlending) {
  51139. animation.enableBlending = parsedAnimation.enableBlending;
  51140. }
  51141. if (parsedAnimation.blendingSpeed) {
  51142. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  51143. }
  51144. for (index = 0; index < parsedAnimation.keys.length; index++) {
  51145. var key = parsedAnimation.keys[index];
  51146. var inTangent;
  51147. var outTangent;
  51148. switch (dataType) {
  51149. case Animation.ANIMATIONTYPE_FLOAT:
  51150. data = key.values[0];
  51151. if (key.values.length >= 1) {
  51152. inTangent = key.values[1];
  51153. }
  51154. if (key.values.length >= 2) {
  51155. outTangent = key.values[2];
  51156. }
  51157. break;
  51158. case Animation.ANIMATIONTYPE_QUATERNION:
  51159. data = BABYLON.Quaternion.FromArray(key.values);
  51160. if (key.values.length >= 8) {
  51161. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  51162. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  51163. inTangent = _inTangent;
  51164. }
  51165. }
  51166. if (key.values.length >= 12) {
  51167. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  51168. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  51169. outTangent = _outTangent;
  51170. }
  51171. }
  51172. break;
  51173. case Animation.ANIMATIONTYPE_MATRIX:
  51174. data = BABYLON.Matrix.FromArray(key.values);
  51175. break;
  51176. case Animation.ANIMATIONTYPE_COLOR3:
  51177. data = BABYLON.Color3.FromArray(key.values);
  51178. break;
  51179. case Animation.ANIMATIONTYPE_VECTOR3:
  51180. default:
  51181. data = BABYLON.Vector3.FromArray(key.values);
  51182. break;
  51183. }
  51184. var keyData = {};
  51185. keyData.frame = key.frame;
  51186. keyData.value = data;
  51187. if (inTangent != undefined) {
  51188. keyData.inTangent = inTangent;
  51189. }
  51190. if (outTangent != undefined) {
  51191. keyData.outTangent = outTangent;
  51192. }
  51193. keys.push(keyData);
  51194. }
  51195. animation.setKeys(keys);
  51196. if (parsedAnimation.ranges) {
  51197. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  51198. data = parsedAnimation.ranges[index];
  51199. animation.createRange(data.name, data.from, data.to);
  51200. }
  51201. }
  51202. return animation;
  51203. };
  51204. /**
  51205. * Appends the serialized animations from the source animations
  51206. * @param source Source containing the animations
  51207. * @param destination Target to store the animations
  51208. */
  51209. Animation.AppendSerializedAnimations = function (source, destination) {
  51210. if (source.animations) {
  51211. destination.animations = [];
  51212. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  51213. var animation = source.animations[animationIndex];
  51214. destination.animations.push(animation.serialize());
  51215. }
  51216. }
  51217. };
  51218. /**
  51219. * Use matrix interpolation instead of using direct key value when animating matrices
  51220. */
  51221. Animation.AllowMatricesInterpolation = false;
  51222. /**
  51223. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  51224. */
  51225. Animation.AllowMatrixDecomposeForInterpolation = true;
  51226. // Statics
  51227. /**
  51228. * Float animation type
  51229. */
  51230. Animation._ANIMATIONTYPE_FLOAT = 0;
  51231. /**
  51232. * Vector3 animation type
  51233. */
  51234. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  51235. /**
  51236. * Quaternion animation type
  51237. */
  51238. Animation._ANIMATIONTYPE_QUATERNION = 2;
  51239. /**
  51240. * Matrix animation type
  51241. */
  51242. Animation._ANIMATIONTYPE_MATRIX = 3;
  51243. /**
  51244. * Color3 animation type
  51245. */
  51246. Animation._ANIMATIONTYPE_COLOR3 = 4;
  51247. /**
  51248. * Vector2 animation type
  51249. */
  51250. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  51251. /**
  51252. * Size animation type
  51253. */
  51254. Animation._ANIMATIONTYPE_SIZE = 6;
  51255. /**
  51256. * Relative Loop Mode
  51257. */
  51258. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  51259. /**
  51260. * Cycle Loop Mode
  51261. */
  51262. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  51263. /**
  51264. * Constant Loop Mode
  51265. */
  51266. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  51267. return Animation;
  51268. }());
  51269. BABYLON.Animation = Animation;
  51270. })(BABYLON || (BABYLON = {}));
  51271. //# sourceMappingURL=babylon.animation.js.map
  51272. var BABYLON;
  51273. (function (BABYLON) {
  51274. /**
  51275. * This class defines the direct association between an animation and a target
  51276. */
  51277. var TargetedAnimation = /** @class */ (function () {
  51278. function TargetedAnimation() {
  51279. }
  51280. return TargetedAnimation;
  51281. }());
  51282. BABYLON.TargetedAnimation = TargetedAnimation;
  51283. /**
  51284. * Use this class to create coordinated animations on multiple targets
  51285. */
  51286. var AnimationGroup = /** @class */ (function () {
  51287. function AnimationGroup(name, scene) {
  51288. if (scene === void 0) { scene = null; }
  51289. this.name = name;
  51290. this._targetedAnimations = new Array();
  51291. this._animatables = new Array();
  51292. this._from = Number.MAX_VALUE;
  51293. this._to = -Number.MAX_VALUE;
  51294. this._speedRatio = 1;
  51295. this.onAnimationEndObservable = new BABYLON.Observable();
  51296. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51297. this._scene.animationGroups.push(this);
  51298. }
  51299. Object.defineProperty(AnimationGroup.prototype, "from", {
  51300. /**
  51301. * Gets the first frame
  51302. */
  51303. get: function () {
  51304. return this._from;
  51305. },
  51306. enumerable: true,
  51307. configurable: true
  51308. });
  51309. Object.defineProperty(AnimationGroup.prototype, "to", {
  51310. /**
  51311. * Gets the last frame
  51312. */
  51313. get: function () {
  51314. return this._to;
  51315. },
  51316. enumerable: true,
  51317. configurable: true
  51318. });
  51319. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  51320. /**
  51321. * Define if the animations are started
  51322. */
  51323. get: function () {
  51324. return this._isStarted;
  51325. },
  51326. enumerable: true,
  51327. configurable: true
  51328. });
  51329. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  51330. /**
  51331. * Gets or sets the speed ratio to use for all animations
  51332. */
  51333. get: function () {
  51334. return this._speedRatio;
  51335. },
  51336. /**
  51337. * Gets or sets the speed ratio to use for all animations
  51338. */
  51339. set: function (value) {
  51340. if (this._speedRatio === value) {
  51341. return;
  51342. }
  51343. this._speedRatio = value;
  51344. for (var index = 0; index < this._animatables.length; index++) {
  51345. var animatable = this._animatables[index];
  51346. animatable.speedRatio = this._speedRatio;
  51347. }
  51348. },
  51349. enumerable: true,
  51350. configurable: true
  51351. });
  51352. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  51353. /**
  51354. * Gets the targeted animations for this animation group
  51355. */
  51356. get: function () {
  51357. return this._targetedAnimations;
  51358. },
  51359. enumerable: true,
  51360. configurable: true
  51361. });
  51362. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  51363. /**
  51364. * returning the list of animatables controlled by this animation group.
  51365. */
  51366. get: function () {
  51367. return this._animatables;
  51368. },
  51369. enumerable: true,
  51370. configurable: true
  51371. });
  51372. /**
  51373. * Add an animation (with its target) in the group
  51374. * @param animation defines the animation we want to add
  51375. * @param target defines the target of the animation
  51376. * @returns the {BABYLON.TargetedAnimation} object
  51377. */
  51378. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  51379. var targetedAnimation = {
  51380. animation: animation,
  51381. target: target
  51382. };
  51383. var keys = animation.getKeys();
  51384. if (this._from > keys[0].frame) {
  51385. this._from = keys[0].frame;
  51386. }
  51387. if (this._to < keys[keys.length - 1].frame) {
  51388. this._to = keys[keys.length - 1].frame;
  51389. }
  51390. this._targetedAnimations.push(targetedAnimation);
  51391. return targetedAnimation;
  51392. };
  51393. /**
  51394. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  51395. * It can add constant keys at begin or end
  51396. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  51397. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  51398. */
  51399. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  51400. if (beginFrame === void 0) { beginFrame = null; }
  51401. if (endFrame === void 0) { endFrame = null; }
  51402. if (beginFrame == null)
  51403. beginFrame = this._from;
  51404. if (endFrame == null)
  51405. endFrame = this._to;
  51406. for (var index = 0; index < this._targetedAnimations.length; index++) {
  51407. var targetedAnimation = this._targetedAnimations[index];
  51408. var keys = targetedAnimation.animation.getKeys();
  51409. var startKey = keys[0];
  51410. var endKey = keys[keys.length - 1];
  51411. if (startKey.frame > beginFrame) {
  51412. var newKey = {
  51413. frame: beginFrame,
  51414. value: startKey.value,
  51415. inTangent: startKey.inTangent,
  51416. outTangent: startKey.outTangent,
  51417. interpolation: startKey.interpolation
  51418. };
  51419. keys.splice(0, 0, newKey);
  51420. }
  51421. if (endKey.frame < endFrame) {
  51422. var newKey = {
  51423. frame: endFrame,
  51424. value: endKey.value,
  51425. inTangent: endKey.outTangent,
  51426. outTangent: endKey.outTangent,
  51427. interpolation: endKey.interpolation
  51428. };
  51429. keys.push(newKey);
  51430. }
  51431. }
  51432. this._from = beginFrame;
  51433. this._to = endFrame;
  51434. return this;
  51435. };
  51436. /**
  51437. * Start all animations on given targets
  51438. * @param loop defines if animations must loop
  51439. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  51440. * @param from defines the from key (optional)
  51441. * @param to defines the to key (optional)
  51442. * @returns the current animation group
  51443. */
  51444. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  51445. var _this = this;
  51446. if (loop === void 0) { loop = false; }
  51447. if (speedRatio === void 0) { speedRatio = 1; }
  51448. if (this._isStarted || this._targetedAnimations.length === 0) {
  51449. return this;
  51450. }
  51451. var _loop_1 = function (targetedAnimation) {
  51452. this_1._animatables.push(this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio, function () {
  51453. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  51454. }));
  51455. };
  51456. var this_1 = this;
  51457. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  51458. var targetedAnimation = _a[_i];
  51459. _loop_1(targetedAnimation);
  51460. }
  51461. this._speedRatio = speedRatio;
  51462. this._isStarted = true;
  51463. return this;
  51464. };
  51465. /**
  51466. * Pause all animations
  51467. */
  51468. AnimationGroup.prototype.pause = function () {
  51469. if (!this._isStarted) {
  51470. return this;
  51471. }
  51472. for (var index = 0; index < this._animatables.length; index++) {
  51473. var animatable = this._animatables[index];
  51474. animatable.pause();
  51475. }
  51476. return this;
  51477. };
  51478. /**
  51479. * Play all animations to initial state
  51480. * This function will start() the animations if they were not started or will restart() them if they were paused
  51481. * @param loop defines if animations must loop
  51482. */
  51483. AnimationGroup.prototype.play = function (loop) {
  51484. if (this.isStarted) {
  51485. if (loop !== undefined) {
  51486. for (var index = 0; index < this._animatables.length; index++) {
  51487. var animatable = this._animatables[index];
  51488. animatable.loopAnimation = loop;
  51489. }
  51490. }
  51491. this.restart();
  51492. }
  51493. else {
  51494. this.start(loop, this._speedRatio);
  51495. }
  51496. return this;
  51497. };
  51498. /**
  51499. * Reset all animations to initial state
  51500. */
  51501. AnimationGroup.prototype.reset = function () {
  51502. if (!this._isStarted) {
  51503. return this;
  51504. }
  51505. for (var index = 0; index < this._animatables.length; index++) {
  51506. var animatable = this._animatables[index];
  51507. animatable.reset();
  51508. }
  51509. return this;
  51510. };
  51511. /**
  51512. * Restart animations from key 0
  51513. */
  51514. AnimationGroup.prototype.restart = function () {
  51515. if (!this._isStarted) {
  51516. return this;
  51517. }
  51518. for (var index = 0; index < this._animatables.length; index++) {
  51519. var animatable = this._animatables[index];
  51520. animatable.restart();
  51521. }
  51522. return this;
  51523. };
  51524. /**
  51525. * Stop all animations
  51526. */
  51527. AnimationGroup.prototype.stop = function () {
  51528. if (!this._isStarted) {
  51529. return this;
  51530. }
  51531. for (var index = 0; index < this._animatables.length; index++) {
  51532. var animatable = this._animatables[index];
  51533. animatable.stop();
  51534. }
  51535. this._isStarted = false;
  51536. return this;
  51537. };
  51538. /**
  51539. * Set animation weight for all animatables
  51540. * @param weight defines the weight to use
  51541. * @return the animationGroup
  51542. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51543. */
  51544. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  51545. for (var index = 0; index < this._animatables.length; index++) {
  51546. var animatable = this._animatables[index];
  51547. animatable.weight = weight;
  51548. }
  51549. return this;
  51550. };
  51551. /**
  51552. * Synchronize and normalize all animatables with a source animatable
  51553. * @param root defines the root animatable to synchronize with
  51554. * @return the animationGroup
  51555. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51556. */
  51557. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  51558. for (var index = 0; index < this._animatables.length; index++) {
  51559. var animatable = this._animatables[index];
  51560. animatable.syncWith(root);
  51561. }
  51562. return this;
  51563. };
  51564. /**
  51565. * Goes to a specific frame in this animation group
  51566. * @param frame the frame number to go to
  51567. * @return the animationGroup
  51568. */
  51569. AnimationGroup.prototype.goToFrame = function (frame) {
  51570. if (!this._isStarted) {
  51571. return this;
  51572. }
  51573. for (var index = 0; index < this._animatables.length; index++) {
  51574. var animatable = this._animatables[index];
  51575. animatable.goToFrame(frame);
  51576. }
  51577. return this;
  51578. };
  51579. /**
  51580. * Dispose all associated resources
  51581. */
  51582. AnimationGroup.prototype.dispose = function () {
  51583. this._targetedAnimations = [];
  51584. this._animatables = [];
  51585. var index = this._scene.animationGroups.indexOf(this);
  51586. if (index > -1) {
  51587. this._scene.animationGroups.splice(index, 1);
  51588. }
  51589. };
  51590. return AnimationGroup;
  51591. }());
  51592. BABYLON.AnimationGroup = AnimationGroup;
  51593. })(BABYLON || (BABYLON = {}));
  51594. //# sourceMappingURL=babylon.animationGroup.js.map
  51595. var BABYLON;
  51596. (function (BABYLON) {
  51597. /**
  51598. * Defines a runtime animation
  51599. */
  51600. var RuntimeAnimation = /** @class */ (function () {
  51601. /**
  51602. * Create a new RuntimeAnimation object
  51603. * @param target defines the target of the animation
  51604. * @param animation defines the source animation object
  51605. * @param scene defines the hosting scene
  51606. * @param host defines the initiating Animatable
  51607. */
  51608. function RuntimeAnimation(target, animation, scene, host) {
  51609. /**
  51610. * The current frame of the runtime animation
  51611. */
  51612. this._currentFrame = 0;
  51613. /**
  51614. * The original value of the runtime animation
  51615. */
  51616. this._originalValue = new Array();
  51617. /**
  51618. * The offsets cache of the runtime animation
  51619. */
  51620. this._offsetsCache = {};
  51621. /**
  51622. * The high limits cache of the runtime animation
  51623. */
  51624. this._highLimitsCache = {};
  51625. /**
  51626. * Specifies if the runtime animation has been stopped
  51627. */
  51628. this._stopped = false;
  51629. /**
  51630. * The blending factor of the runtime animation
  51631. */
  51632. this._blendingFactor = 0;
  51633. /**
  51634. * The target path of the runtime animation
  51635. */
  51636. this._targetPath = "";
  51637. /**
  51638. * The weight of the runtime animation
  51639. */
  51640. this._weight = 1.0;
  51641. /**
  51642. * The ratio offset of the runtime animation
  51643. */
  51644. this._ratioOffset = 0;
  51645. /**
  51646. * The previous delay of the runtime animation
  51647. */
  51648. this._previousDelay = 0;
  51649. /**
  51650. * The previous ratio of the runtime animation
  51651. */
  51652. this._previousRatio = 0;
  51653. this._animation = animation;
  51654. this._target = target;
  51655. this._scene = scene;
  51656. this._host = host;
  51657. animation._runtimeAnimations.push(this);
  51658. }
  51659. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  51660. /**
  51661. * Gets the current frame of the runtime animation
  51662. */
  51663. get: function () {
  51664. return this._currentFrame;
  51665. },
  51666. enumerable: true,
  51667. configurable: true
  51668. });
  51669. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  51670. /**
  51671. * Gets the weight of the runtime animation
  51672. */
  51673. get: function () {
  51674. return this._weight;
  51675. },
  51676. enumerable: true,
  51677. configurable: true
  51678. });
  51679. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  51680. /**
  51681. * Gets the current value of the runtime animation
  51682. */
  51683. get: function () {
  51684. return this._currentValue;
  51685. },
  51686. enumerable: true,
  51687. configurable: true
  51688. });
  51689. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  51690. /**
  51691. * Gets the target path of the runtime animation
  51692. */
  51693. get: function () {
  51694. return this._targetPath;
  51695. },
  51696. enumerable: true,
  51697. configurable: true
  51698. });
  51699. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  51700. /**
  51701. * Gets the actual target of the runtime animation
  51702. */
  51703. get: function () {
  51704. return this._activeTarget;
  51705. },
  51706. enumerable: true,
  51707. configurable: true
  51708. });
  51709. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  51710. /**
  51711. * Gets the animation from the runtime animation
  51712. */
  51713. get: function () {
  51714. return this._animation;
  51715. },
  51716. enumerable: true,
  51717. configurable: true
  51718. });
  51719. /**
  51720. * Resets the runtime animation to the beginning
  51721. * @param restoreOriginal defines whether to restore the target property to the original value
  51722. */
  51723. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  51724. if (restoreOriginal === void 0) { restoreOriginal = false; }
  51725. if (restoreOriginal) {
  51726. if (this._target instanceof Array) {
  51727. var index = 0;
  51728. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  51729. var target = _a[_i];
  51730. if (this._originalValue[index] !== undefined) {
  51731. this._setValue(target, this._originalValue[index], -1);
  51732. }
  51733. index++;
  51734. }
  51735. }
  51736. else {
  51737. if (this._originalValue[0] !== undefined) {
  51738. this._setValue(this._target, this._originalValue[0], -1);
  51739. }
  51740. }
  51741. }
  51742. this._offsetsCache = {};
  51743. this._highLimitsCache = {};
  51744. this._currentFrame = 0;
  51745. this._blendingFactor = 0;
  51746. this._originalValue = new Array();
  51747. };
  51748. /**
  51749. * Specifies if the runtime animation is stopped
  51750. * @returns Boolean specifying if the runtime animation is stopped
  51751. */
  51752. RuntimeAnimation.prototype.isStopped = function () {
  51753. return this._stopped;
  51754. };
  51755. /**
  51756. * Disposes of the runtime animation
  51757. */
  51758. RuntimeAnimation.prototype.dispose = function () {
  51759. var index = this._animation.runtimeAnimations.indexOf(this);
  51760. if (index > -1) {
  51761. this._animation.runtimeAnimations.splice(index, 1);
  51762. }
  51763. };
  51764. /**
  51765. * Interpolates the animation from the current frame
  51766. * @param currentFrame The frame to interpolate the animation to
  51767. * @param repeatCount The number of times that the animation should loop
  51768. * @param loopMode The type of looping mode to use
  51769. * @param offsetValue Animation offset value
  51770. * @param highLimitValue The high limit value
  51771. * @returns The interpolated value
  51772. */
  51773. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  51774. this._currentFrame = currentFrame;
  51775. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  51776. this._workValue = BABYLON.Matrix.Zero();
  51777. }
  51778. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  51779. };
  51780. /**
  51781. * Apply the interpolated value to the target
  51782. * @param currentValue defines the value computed by the animation
  51783. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  51784. */
  51785. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  51786. if (weight === void 0) { weight = 1.0; }
  51787. if (this._target instanceof Array) {
  51788. var index = 0;
  51789. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  51790. var target = _a[_i];
  51791. this._setValue(target, currentValue, weight, index);
  51792. index++;
  51793. }
  51794. }
  51795. else {
  51796. this._setValue(this._target, currentValue, weight);
  51797. }
  51798. };
  51799. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  51800. if (targetIndex === void 0) { targetIndex = 0; }
  51801. // Set value
  51802. var path;
  51803. var destination;
  51804. var targetPropertyPath = this._animation.targetPropertyPath;
  51805. if (targetPropertyPath.length > 1) {
  51806. var property = target[targetPropertyPath[0]];
  51807. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  51808. property = property[targetPropertyPath[index]];
  51809. }
  51810. path = targetPropertyPath[targetPropertyPath.length - 1];
  51811. destination = property;
  51812. }
  51813. else {
  51814. path = targetPropertyPath[0];
  51815. destination = target;
  51816. }
  51817. this._targetPath = path;
  51818. this._activeTarget = destination;
  51819. this._weight = weight;
  51820. if (this._originalValue[targetIndex] === undefined) {
  51821. var originalValue = void 0;
  51822. if (destination.getRestPose && path === "_matrix") { // For bones
  51823. originalValue = destination.getRestPose();
  51824. }
  51825. else {
  51826. originalValue = destination[path];
  51827. }
  51828. if (originalValue && originalValue.clone) {
  51829. this._originalValue[targetIndex] = originalValue.clone();
  51830. }
  51831. else {
  51832. this._originalValue[targetIndex] = originalValue;
  51833. }
  51834. }
  51835. // Blending
  51836. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  51837. if (enableBlending && this._blendingFactor <= 1.0) {
  51838. if (!this._originalBlendValue) {
  51839. var originalValue = destination[path];
  51840. if (originalValue.clone) {
  51841. this._originalBlendValue = originalValue.clone();
  51842. }
  51843. else {
  51844. this._originalBlendValue = originalValue;
  51845. }
  51846. }
  51847. if (this._originalBlendValue.m) { // Matrix
  51848. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  51849. if (this._currentValue) {
  51850. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51851. }
  51852. else {
  51853. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51854. }
  51855. }
  51856. else {
  51857. if (this._currentValue) {
  51858. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51859. }
  51860. else {
  51861. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51862. }
  51863. }
  51864. }
  51865. else {
  51866. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51867. }
  51868. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  51869. this._blendingFactor += blendingSpeed;
  51870. }
  51871. else {
  51872. this._currentValue = currentValue;
  51873. }
  51874. if (weight !== -1.0) {
  51875. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  51876. }
  51877. else {
  51878. destination[path] = this._currentValue;
  51879. }
  51880. if (target.markAsDirty) {
  51881. target.markAsDirty(this._animation.targetProperty);
  51882. }
  51883. };
  51884. /**
  51885. * Gets the loop pmode of the runtime animation
  51886. * @returns Loop Mode
  51887. */
  51888. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  51889. if (this._target && this._target.animationPropertiesOverride) {
  51890. return this._target.animationPropertiesOverride.loopMode;
  51891. }
  51892. return this._animation.loopMode;
  51893. };
  51894. /**
  51895. * Move the current animation to a given frame
  51896. * @param frame defines the frame to move to
  51897. */
  51898. RuntimeAnimation.prototype.goToFrame = function (frame) {
  51899. var keys = this._animation.getKeys();
  51900. if (frame < keys[0].frame) {
  51901. frame = keys[0].frame;
  51902. }
  51903. else if (frame > keys[keys.length - 1].frame) {
  51904. frame = keys[keys.length - 1].frame;
  51905. }
  51906. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  51907. this.setValue(currentValue, -1);
  51908. };
  51909. /**
  51910. * @hidden Internal use only
  51911. */
  51912. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  51913. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  51914. this._ratioOffset = this._previousRatio - newRatio;
  51915. };
  51916. /**
  51917. * Execute the current animation
  51918. * @param delay defines the delay to add to the current frame
  51919. * @param from defines the lower bound of the animation range
  51920. * @param to defines the upper bound of the animation range
  51921. * @param loop defines if the current animation must loop
  51922. * @param speedRatio defines the current speed ratio
  51923. * @param weight defines the weight of the animation (default is -1 so no weight)
  51924. * @returns a boolean indicating if the animation has ended
  51925. */
  51926. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  51927. if (weight === void 0) { weight = -1.0; }
  51928. var targetPropertyPath = this._animation.targetPropertyPath;
  51929. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  51930. this._stopped = true;
  51931. return false;
  51932. }
  51933. var returnValue = true;
  51934. var keys = this._animation.getKeys();
  51935. // Adding a start key at frame 0 if missing
  51936. if (keys[0].frame !== 0) {
  51937. var newKey = { frame: 0, value: keys[0].value };
  51938. keys.splice(0, 0, newKey);
  51939. }
  51940. // Check limits
  51941. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  51942. from = keys[0].frame;
  51943. }
  51944. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  51945. to = keys[keys.length - 1].frame;
  51946. }
  51947. //to and from cannot be the same key
  51948. if (from === to) {
  51949. if (from > keys[0].frame) {
  51950. from--;
  51951. }
  51952. else if (to < keys[keys.length - 1].frame) {
  51953. to++;
  51954. }
  51955. }
  51956. // Compute ratio
  51957. var range = to - from;
  51958. var offsetValue;
  51959. // ratio represents the frame delta between from and to
  51960. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  51961. var highLimitValue = 0;
  51962. this._previousDelay = delay;
  51963. this._previousRatio = ratio;
  51964. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) { // If we are out of range and not looping get back to caller
  51965. returnValue = false;
  51966. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  51967. }
  51968. else {
  51969. // Get max value if required
  51970. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  51971. var keyOffset = to.toString() + from.toString();
  51972. if (!this._offsetsCache[keyOffset]) {
  51973. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51974. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51975. switch (this._animation.dataType) {
  51976. // Float
  51977. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51978. this._offsetsCache[keyOffset] = toValue - fromValue;
  51979. break;
  51980. // Quaternion
  51981. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51982. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51983. break;
  51984. // Vector3
  51985. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51986. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51987. // Vector2
  51988. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51989. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51990. // Size
  51991. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51992. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51993. // Color3
  51994. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51995. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51996. default:
  51997. break;
  51998. }
  51999. this._highLimitsCache[keyOffset] = toValue;
  52000. }
  52001. highLimitValue = this._highLimitsCache[keyOffset];
  52002. offsetValue = this._offsetsCache[keyOffset];
  52003. }
  52004. }
  52005. if (offsetValue === undefined) {
  52006. switch (this._animation.dataType) {
  52007. // Float
  52008. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  52009. offsetValue = 0;
  52010. break;
  52011. // Quaternion
  52012. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  52013. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  52014. break;
  52015. // Vector3
  52016. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  52017. offsetValue = BABYLON.Vector3.Zero();
  52018. break;
  52019. // Vector2
  52020. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  52021. offsetValue = BABYLON.Vector2.Zero();
  52022. break;
  52023. // Size
  52024. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  52025. offsetValue = BABYLON.Size.Zero();
  52026. break;
  52027. // Color3
  52028. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  52029. offsetValue = BABYLON.Color3.Black();
  52030. }
  52031. }
  52032. // Compute value
  52033. var repeatCount = (ratio / range) >> 0;
  52034. var currentFrame = returnValue ? from + ratio % range : to;
  52035. // Need to normalize?
  52036. if (this._host && this._host.syncRoot) {
  52037. var syncRoot = this._host.syncRoot;
  52038. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  52039. currentFrame = from + (to - from) * hostNormalizedFrame;
  52040. }
  52041. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  52042. // Set value
  52043. this.setValue(currentValue, weight);
  52044. // Check events
  52045. var events = this._animation.getEvents();
  52046. for (var index = 0; index < events.length; index++) {
  52047. // Make sure current frame has passed event frame and that event frame is within the current range
  52048. // Also, handle both forward and reverse animations
  52049. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  52050. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  52051. var event = events[index];
  52052. if (!event.isDone) {
  52053. // If event should be done only once, remove it.
  52054. if (event.onlyOnce) {
  52055. events.splice(index, 1);
  52056. index--;
  52057. }
  52058. event.isDone = true;
  52059. event.action();
  52060. } // Don't do anything if the event has already be done.
  52061. }
  52062. else if (events[index].isDone && !events[index].onlyOnce) {
  52063. // reset event, the animation is looping
  52064. events[index].isDone = false;
  52065. }
  52066. }
  52067. if (!returnValue) {
  52068. this._stopped = true;
  52069. }
  52070. return returnValue;
  52071. };
  52072. return RuntimeAnimation;
  52073. }());
  52074. BABYLON.RuntimeAnimation = RuntimeAnimation;
  52075. })(BABYLON || (BABYLON = {}));
  52076. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  52077. var BABYLON;
  52078. (function (BABYLON) {
  52079. var Animatable = /** @class */ (function () {
  52080. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  52081. if (fromFrame === void 0) { fromFrame = 0; }
  52082. if (toFrame === void 0) { toFrame = 100; }
  52083. if (loopAnimation === void 0) { loopAnimation = false; }
  52084. if (speedRatio === void 0) { speedRatio = 1.0; }
  52085. this.target = target;
  52086. this.fromFrame = fromFrame;
  52087. this.toFrame = toFrame;
  52088. this.loopAnimation = loopAnimation;
  52089. this.onAnimationEnd = onAnimationEnd;
  52090. this._localDelayOffset = null;
  52091. this._pausedDelay = null;
  52092. this._runtimeAnimations = new Array();
  52093. this._paused = false;
  52094. this._speedRatio = 1;
  52095. this._weight = -1.0;
  52096. this.animationStarted = false;
  52097. this._scene = scene;
  52098. if (animations) {
  52099. this.appendAnimations(target, animations);
  52100. }
  52101. this._speedRatio = speedRatio;
  52102. scene._activeAnimatables.push(this);
  52103. }
  52104. Object.defineProperty(Animatable.prototype, "syncRoot", {
  52105. /**
  52106. * Gets the root Animatable used to synchronize and normalize animations
  52107. */
  52108. get: function () {
  52109. return this._syncRoot;
  52110. },
  52111. enumerable: true,
  52112. configurable: true
  52113. });
  52114. Object.defineProperty(Animatable.prototype, "masterFrame", {
  52115. /**
  52116. * Gets the current frame of the first RuntimeAnimation
  52117. * Used to synchronize Animatables
  52118. */
  52119. get: function () {
  52120. if (this._runtimeAnimations.length === 0) {
  52121. return 0;
  52122. }
  52123. return this._runtimeAnimations[0].currentFrame;
  52124. },
  52125. enumerable: true,
  52126. configurable: true
  52127. });
  52128. Object.defineProperty(Animatable.prototype, "weight", {
  52129. /**
  52130. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  52131. */
  52132. get: function () {
  52133. return this._weight;
  52134. },
  52135. set: function (value) {
  52136. if (value === -1) { // -1 is ok and means no weight
  52137. this._weight = -1;
  52138. return;
  52139. }
  52140. // Else weight must be in [0, 1] range
  52141. this._weight = Math.min(Math.max(value, 0), 1.0);
  52142. },
  52143. enumerable: true,
  52144. configurable: true
  52145. });
  52146. Object.defineProperty(Animatable.prototype, "speedRatio", {
  52147. /**
  52148. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  52149. */
  52150. get: function () {
  52151. return this._speedRatio;
  52152. },
  52153. set: function (value) {
  52154. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  52155. var animation = this._runtimeAnimations[index];
  52156. animation._prepareForSpeedRatioChange(value);
  52157. }
  52158. this._speedRatio = value;
  52159. },
  52160. enumerable: true,
  52161. configurable: true
  52162. });
  52163. // Methods
  52164. /**
  52165. * Synchronize and normalize current Animatable with a source Animatable
  52166. * This is useful when using animation weights and when animations are not of the same length
  52167. * @param root defines the root Animatable to synchronize with
  52168. * @returns the current Animatable
  52169. */
  52170. Animatable.prototype.syncWith = function (root) {
  52171. this._syncRoot = root;
  52172. if (root) {
  52173. // Make sure this animatable will animate after the root
  52174. var index = this._scene._activeAnimatables.indexOf(this);
  52175. if (index > -1) {
  52176. this._scene._activeAnimatables.splice(index, 1);
  52177. this._scene._activeAnimatables.push(this);
  52178. }
  52179. }
  52180. return this;
  52181. };
  52182. Animatable.prototype.getAnimations = function () {
  52183. return this._runtimeAnimations;
  52184. };
  52185. Animatable.prototype.appendAnimations = function (target, animations) {
  52186. for (var index = 0; index < animations.length; index++) {
  52187. var animation = animations[index];
  52188. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  52189. }
  52190. };
  52191. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  52192. var runtimeAnimations = this._runtimeAnimations;
  52193. for (var index = 0; index < runtimeAnimations.length; index++) {
  52194. if (runtimeAnimations[index].animation.targetProperty === property) {
  52195. return runtimeAnimations[index].animation;
  52196. }
  52197. }
  52198. return null;
  52199. };
  52200. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  52201. var runtimeAnimations = this._runtimeAnimations;
  52202. for (var index = 0; index < runtimeAnimations.length; index++) {
  52203. if (runtimeAnimations[index].animation.targetProperty === property) {
  52204. return runtimeAnimations[index];
  52205. }
  52206. }
  52207. return null;
  52208. };
  52209. Animatable.prototype.reset = function () {
  52210. var runtimeAnimations = this._runtimeAnimations;
  52211. for (var index = 0; index < runtimeAnimations.length; index++) {
  52212. runtimeAnimations[index].reset(true);
  52213. }
  52214. this._localDelayOffset = null;
  52215. this._pausedDelay = null;
  52216. };
  52217. Animatable.prototype.enableBlending = function (blendingSpeed) {
  52218. var runtimeAnimations = this._runtimeAnimations;
  52219. for (var index = 0; index < runtimeAnimations.length; index++) {
  52220. runtimeAnimations[index].animation.enableBlending = true;
  52221. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  52222. }
  52223. };
  52224. Animatable.prototype.disableBlending = function () {
  52225. var runtimeAnimations = this._runtimeAnimations;
  52226. for (var index = 0; index < runtimeAnimations.length; index++) {
  52227. runtimeAnimations[index].animation.enableBlending = false;
  52228. }
  52229. };
  52230. Animatable.prototype.goToFrame = function (frame) {
  52231. var runtimeAnimations = this._runtimeAnimations;
  52232. if (runtimeAnimations[0]) {
  52233. var fps = runtimeAnimations[0].animation.framePerSecond;
  52234. var currentFrame = runtimeAnimations[0].currentFrame;
  52235. var adjustTime = frame - currentFrame;
  52236. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  52237. if (this._localDelayOffset === null) {
  52238. this._localDelayOffset = 0;
  52239. }
  52240. this._localDelayOffset -= delay;
  52241. }
  52242. for (var index = 0; index < runtimeAnimations.length; index++) {
  52243. runtimeAnimations[index].goToFrame(frame);
  52244. }
  52245. };
  52246. Animatable.prototype.pause = function () {
  52247. if (this._paused) {
  52248. return;
  52249. }
  52250. this._paused = true;
  52251. };
  52252. Animatable.prototype.restart = function () {
  52253. this._paused = false;
  52254. };
  52255. Animatable.prototype.stop = function (animationName) {
  52256. if (animationName) {
  52257. var idx = this._scene._activeAnimatables.indexOf(this);
  52258. if (idx > -1) {
  52259. var runtimeAnimations = this._runtimeAnimations;
  52260. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  52261. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  52262. continue;
  52263. }
  52264. runtimeAnimations[index].dispose();
  52265. runtimeAnimations.splice(index, 1);
  52266. }
  52267. if (runtimeAnimations.length == 0) {
  52268. this._scene._activeAnimatables.splice(idx, 1);
  52269. if (this.onAnimationEnd) {
  52270. this.onAnimationEnd();
  52271. }
  52272. }
  52273. }
  52274. }
  52275. else {
  52276. var index = this._scene._activeAnimatables.indexOf(this);
  52277. if (index > -1) {
  52278. this._scene._activeAnimatables.splice(index, 1);
  52279. var runtimeAnimations = this._runtimeAnimations;
  52280. for (var index = 0; index < runtimeAnimations.length; index++) {
  52281. runtimeAnimations[index].dispose();
  52282. }
  52283. if (this.onAnimationEnd) {
  52284. this.onAnimationEnd();
  52285. }
  52286. }
  52287. }
  52288. };
  52289. Animatable.prototype._animate = function (delay) {
  52290. if (this._paused) {
  52291. this.animationStarted = false;
  52292. if (this._pausedDelay === null) {
  52293. this._pausedDelay = delay;
  52294. }
  52295. return true;
  52296. }
  52297. if (this._localDelayOffset === null) {
  52298. this._localDelayOffset = delay;
  52299. this._pausedDelay = null;
  52300. }
  52301. else if (this._pausedDelay !== null) {
  52302. this._localDelayOffset += delay - this._pausedDelay;
  52303. this._pausedDelay = null;
  52304. }
  52305. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  52306. return true;
  52307. }
  52308. // Animating
  52309. var running = false;
  52310. var runtimeAnimations = this._runtimeAnimations;
  52311. var index;
  52312. for (index = 0; index < runtimeAnimations.length; index++) {
  52313. var animation = runtimeAnimations[index];
  52314. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  52315. running = running || isRunning;
  52316. }
  52317. this.animationStarted = running;
  52318. if (!running) {
  52319. // Remove from active animatables
  52320. index = this._scene._activeAnimatables.indexOf(this);
  52321. this._scene._activeAnimatables.splice(index, 1);
  52322. // Dispose all runtime animations
  52323. for (index = 0; index < runtimeAnimations.length; index++) {
  52324. runtimeAnimations[index].dispose();
  52325. }
  52326. }
  52327. if (!running && this.onAnimationEnd) {
  52328. this.onAnimationEnd();
  52329. this.onAnimationEnd = null;
  52330. }
  52331. return running;
  52332. };
  52333. return Animatable;
  52334. }());
  52335. BABYLON.Animatable = Animatable;
  52336. })(BABYLON || (BABYLON = {}));
  52337. //# sourceMappingURL=babylon.animatable.js.map
  52338. var BABYLON;
  52339. (function (BABYLON) {
  52340. var EasingFunction = /** @class */ (function () {
  52341. function EasingFunction() {
  52342. // Properties
  52343. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  52344. }
  52345. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  52346. get: function () {
  52347. return EasingFunction._EASINGMODE_EASEIN;
  52348. },
  52349. enumerable: true,
  52350. configurable: true
  52351. });
  52352. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  52353. get: function () {
  52354. return EasingFunction._EASINGMODE_EASEOUT;
  52355. },
  52356. enumerable: true,
  52357. configurable: true
  52358. });
  52359. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  52360. get: function () {
  52361. return EasingFunction._EASINGMODE_EASEINOUT;
  52362. },
  52363. enumerable: true,
  52364. configurable: true
  52365. });
  52366. EasingFunction.prototype.setEasingMode = function (easingMode) {
  52367. var n = Math.min(Math.max(easingMode, 0), 2);
  52368. this._easingMode = n;
  52369. };
  52370. EasingFunction.prototype.getEasingMode = function () {
  52371. return this._easingMode;
  52372. };
  52373. EasingFunction.prototype.easeInCore = function (gradient) {
  52374. throw new Error('You must implement this method');
  52375. };
  52376. EasingFunction.prototype.ease = function (gradient) {
  52377. switch (this._easingMode) {
  52378. case EasingFunction.EASINGMODE_EASEIN:
  52379. return this.easeInCore(gradient);
  52380. case EasingFunction.EASINGMODE_EASEOUT:
  52381. return (1 - this.easeInCore(1 - gradient));
  52382. }
  52383. if (gradient >= 0.5) {
  52384. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  52385. }
  52386. return (this.easeInCore(gradient * 2) * 0.5);
  52387. };
  52388. //Statics
  52389. EasingFunction._EASINGMODE_EASEIN = 0;
  52390. EasingFunction._EASINGMODE_EASEOUT = 1;
  52391. EasingFunction._EASINGMODE_EASEINOUT = 2;
  52392. return EasingFunction;
  52393. }());
  52394. BABYLON.EasingFunction = EasingFunction;
  52395. var CircleEase = /** @class */ (function (_super) {
  52396. __extends(CircleEase, _super);
  52397. function CircleEase() {
  52398. return _super !== null && _super.apply(this, arguments) || this;
  52399. }
  52400. CircleEase.prototype.easeInCore = function (gradient) {
  52401. gradient = Math.max(0, Math.min(1, gradient));
  52402. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  52403. };
  52404. return CircleEase;
  52405. }(EasingFunction));
  52406. BABYLON.CircleEase = CircleEase;
  52407. var BackEase = /** @class */ (function (_super) {
  52408. __extends(BackEase, _super);
  52409. function BackEase(amplitude) {
  52410. if (amplitude === void 0) { amplitude = 1; }
  52411. var _this = _super.call(this) || this;
  52412. _this.amplitude = amplitude;
  52413. return _this;
  52414. }
  52415. BackEase.prototype.easeInCore = function (gradient) {
  52416. var num = Math.max(0, this.amplitude);
  52417. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  52418. };
  52419. return BackEase;
  52420. }(EasingFunction));
  52421. BABYLON.BackEase = BackEase;
  52422. var BounceEase = /** @class */ (function (_super) {
  52423. __extends(BounceEase, _super);
  52424. function BounceEase(bounces, bounciness) {
  52425. if (bounces === void 0) { bounces = 3; }
  52426. if (bounciness === void 0) { bounciness = 2; }
  52427. var _this = _super.call(this) || this;
  52428. _this.bounces = bounces;
  52429. _this.bounciness = bounciness;
  52430. return _this;
  52431. }
  52432. BounceEase.prototype.easeInCore = function (gradient) {
  52433. var y = Math.max(0.0, this.bounces);
  52434. var bounciness = this.bounciness;
  52435. if (bounciness <= 1.0) {
  52436. bounciness = 1.001;
  52437. }
  52438. var num9 = Math.pow(bounciness, y);
  52439. var num5 = 1.0 - bounciness;
  52440. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  52441. var num15 = gradient * num4;
  52442. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  52443. var num3 = Math.floor(num65);
  52444. var num13 = num3 + 1.0;
  52445. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  52446. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  52447. var num7 = (num8 + num12) * 0.5;
  52448. var num6 = gradient - num7;
  52449. var num2 = num7 - num8;
  52450. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  52451. };
  52452. return BounceEase;
  52453. }(EasingFunction));
  52454. BABYLON.BounceEase = BounceEase;
  52455. var CubicEase = /** @class */ (function (_super) {
  52456. __extends(CubicEase, _super);
  52457. function CubicEase() {
  52458. return _super !== null && _super.apply(this, arguments) || this;
  52459. }
  52460. CubicEase.prototype.easeInCore = function (gradient) {
  52461. return (gradient * gradient * gradient);
  52462. };
  52463. return CubicEase;
  52464. }(EasingFunction));
  52465. BABYLON.CubicEase = CubicEase;
  52466. var ElasticEase = /** @class */ (function (_super) {
  52467. __extends(ElasticEase, _super);
  52468. function ElasticEase(oscillations, springiness) {
  52469. if (oscillations === void 0) { oscillations = 3; }
  52470. if (springiness === void 0) { springiness = 3; }
  52471. var _this = _super.call(this) || this;
  52472. _this.oscillations = oscillations;
  52473. _this.springiness = springiness;
  52474. return _this;
  52475. }
  52476. ElasticEase.prototype.easeInCore = function (gradient) {
  52477. var num2;
  52478. var num3 = Math.max(0.0, this.oscillations);
  52479. var num = Math.max(0.0, this.springiness);
  52480. if (num == 0) {
  52481. num2 = gradient;
  52482. }
  52483. else {
  52484. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  52485. }
  52486. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  52487. };
  52488. return ElasticEase;
  52489. }(EasingFunction));
  52490. BABYLON.ElasticEase = ElasticEase;
  52491. var ExponentialEase = /** @class */ (function (_super) {
  52492. __extends(ExponentialEase, _super);
  52493. function ExponentialEase(exponent) {
  52494. if (exponent === void 0) { exponent = 2; }
  52495. var _this = _super.call(this) || this;
  52496. _this.exponent = exponent;
  52497. return _this;
  52498. }
  52499. ExponentialEase.prototype.easeInCore = function (gradient) {
  52500. if (this.exponent <= 0) {
  52501. return gradient;
  52502. }
  52503. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  52504. };
  52505. return ExponentialEase;
  52506. }(EasingFunction));
  52507. BABYLON.ExponentialEase = ExponentialEase;
  52508. var PowerEase = /** @class */ (function (_super) {
  52509. __extends(PowerEase, _super);
  52510. function PowerEase(power) {
  52511. if (power === void 0) { power = 2; }
  52512. var _this = _super.call(this) || this;
  52513. _this.power = power;
  52514. return _this;
  52515. }
  52516. PowerEase.prototype.easeInCore = function (gradient) {
  52517. var y = Math.max(0.0, this.power);
  52518. return Math.pow(gradient, y);
  52519. };
  52520. return PowerEase;
  52521. }(EasingFunction));
  52522. BABYLON.PowerEase = PowerEase;
  52523. var QuadraticEase = /** @class */ (function (_super) {
  52524. __extends(QuadraticEase, _super);
  52525. function QuadraticEase() {
  52526. return _super !== null && _super.apply(this, arguments) || this;
  52527. }
  52528. QuadraticEase.prototype.easeInCore = function (gradient) {
  52529. return (gradient * gradient);
  52530. };
  52531. return QuadraticEase;
  52532. }(EasingFunction));
  52533. BABYLON.QuadraticEase = QuadraticEase;
  52534. var QuarticEase = /** @class */ (function (_super) {
  52535. __extends(QuarticEase, _super);
  52536. function QuarticEase() {
  52537. return _super !== null && _super.apply(this, arguments) || this;
  52538. }
  52539. QuarticEase.prototype.easeInCore = function (gradient) {
  52540. return (gradient * gradient * gradient * gradient);
  52541. };
  52542. return QuarticEase;
  52543. }(EasingFunction));
  52544. BABYLON.QuarticEase = QuarticEase;
  52545. var QuinticEase = /** @class */ (function (_super) {
  52546. __extends(QuinticEase, _super);
  52547. function QuinticEase() {
  52548. return _super !== null && _super.apply(this, arguments) || this;
  52549. }
  52550. QuinticEase.prototype.easeInCore = function (gradient) {
  52551. return (gradient * gradient * gradient * gradient * gradient);
  52552. };
  52553. return QuinticEase;
  52554. }(EasingFunction));
  52555. BABYLON.QuinticEase = QuinticEase;
  52556. var SineEase = /** @class */ (function (_super) {
  52557. __extends(SineEase, _super);
  52558. function SineEase() {
  52559. return _super !== null && _super.apply(this, arguments) || this;
  52560. }
  52561. SineEase.prototype.easeInCore = function (gradient) {
  52562. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  52563. };
  52564. return SineEase;
  52565. }(EasingFunction));
  52566. BABYLON.SineEase = SineEase;
  52567. var BezierCurveEase = /** @class */ (function (_super) {
  52568. __extends(BezierCurveEase, _super);
  52569. function BezierCurveEase(x1, y1, x2, y2) {
  52570. if (x1 === void 0) { x1 = 0; }
  52571. if (y1 === void 0) { y1 = 0; }
  52572. if (x2 === void 0) { x2 = 1; }
  52573. if (y2 === void 0) { y2 = 1; }
  52574. var _this = _super.call(this) || this;
  52575. _this.x1 = x1;
  52576. _this.y1 = y1;
  52577. _this.x2 = x2;
  52578. _this.y2 = y2;
  52579. return _this;
  52580. }
  52581. BezierCurveEase.prototype.easeInCore = function (gradient) {
  52582. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  52583. };
  52584. return BezierCurveEase;
  52585. }(EasingFunction));
  52586. BABYLON.BezierCurveEase = BezierCurveEase;
  52587. })(BABYLON || (BABYLON = {}));
  52588. //# sourceMappingURL=babylon.easing.js.map
  52589. var BABYLON;
  52590. (function (BABYLON) {
  52591. /**
  52592. * A Condition applied to an Action
  52593. */
  52594. var Condition = /** @class */ (function () {
  52595. /**
  52596. * Creates a new Condition
  52597. * @param actionManager the manager of the action the condition is applied to
  52598. */
  52599. function Condition(actionManager) {
  52600. this._actionManager = actionManager;
  52601. }
  52602. /**
  52603. * Check if the current condition is valid
  52604. * @returns a boolean
  52605. */
  52606. Condition.prototype.isValid = function () {
  52607. return true;
  52608. };
  52609. /**
  52610. * Internal only
  52611. * @hidden
  52612. */
  52613. Condition.prototype._getProperty = function (propertyPath) {
  52614. return this._actionManager._getProperty(propertyPath);
  52615. };
  52616. /**
  52617. * Internal only
  52618. * @hidden
  52619. */
  52620. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  52621. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52622. };
  52623. /**
  52624. * Serialize placeholder for child classes
  52625. * @returns the serialized object
  52626. */
  52627. Condition.prototype.serialize = function () {
  52628. };
  52629. /**
  52630. * Internal only
  52631. * @hidden
  52632. */
  52633. Condition.prototype._serialize = function (serializedCondition) {
  52634. return {
  52635. type: 2,
  52636. children: [],
  52637. name: serializedCondition.name,
  52638. properties: serializedCondition.properties
  52639. };
  52640. };
  52641. return Condition;
  52642. }());
  52643. BABYLON.Condition = Condition;
  52644. /**
  52645. * Defines specific conditional operators as extensions of Condition
  52646. */
  52647. var ValueCondition = /** @class */ (function (_super) {
  52648. __extends(ValueCondition, _super);
  52649. /**
  52650. * Creates a new ValueCondition
  52651. * @param actionManager manager for the action the condition applies to
  52652. * @param target for the action
  52653. * @param propertyPath path to specify the property of the target the conditional operator uses
  52654. * @param value the value compared by the conditional operator against the current value of the property
  52655. * @param operator the conditional operator, default ValueCondition.IsEqual
  52656. */
  52657. function ValueCondition(actionManager, target,
  52658. /** path to specify the property of the target the conditional operator uses */
  52659. propertyPath,
  52660. /** the value compared by the conditional operator against the current value of the property */
  52661. value,
  52662. /** the conditional operator, default ValueCondition.IsEqual */
  52663. operator) {
  52664. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  52665. var _this = _super.call(this, actionManager) || this;
  52666. _this.propertyPath = propertyPath;
  52667. _this.value = value;
  52668. _this.operator = operator;
  52669. _this._target = target;
  52670. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  52671. _this._property = _this._getProperty(_this.propertyPath);
  52672. return _this;
  52673. }
  52674. Object.defineProperty(ValueCondition, "IsEqual", {
  52675. /**
  52676. * returns the number for IsEqual
  52677. */
  52678. get: function () {
  52679. return ValueCondition._IsEqual;
  52680. },
  52681. enumerable: true,
  52682. configurable: true
  52683. });
  52684. Object.defineProperty(ValueCondition, "IsDifferent", {
  52685. /**
  52686. * Returns the number for IsDifferent
  52687. */
  52688. get: function () {
  52689. return ValueCondition._IsDifferent;
  52690. },
  52691. enumerable: true,
  52692. configurable: true
  52693. });
  52694. Object.defineProperty(ValueCondition, "IsGreater", {
  52695. /**
  52696. * Returns the number for IsGreater
  52697. */
  52698. get: function () {
  52699. return ValueCondition._IsGreater;
  52700. },
  52701. enumerable: true,
  52702. configurable: true
  52703. });
  52704. Object.defineProperty(ValueCondition, "IsLesser", {
  52705. /**
  52706. * Returns the number for IsLesser
  52707. */
  52708. get: function () {
  52709. return ValueCondition._IsLesser;
  52710. },
  52711. enumerable: true,
  52712. configurable: true
  52713. });
  52714. /**
  52715. * Compares the given value with the property value for the specified conditional operator
  52716. * @returns the result of the comparison
  52717. */
  52718. ValueCondition.prototype.isValid = function () {
  52719. switch (this.operator) {
  52720. case ValueCondition.IsGreater:
  52721. return this._effectiveTarget[this._property] > this.value;
  52722. case ValueCondition.IsLesser:
  52723. return this._effectiveTarget[this._property] < this.value;
  52724. case ValueCondition.IsEqual:
  52725. case ValueCondition.IsDifferent:
  52726. var check;
  52727. if (this.value.equals) {
  52728. check = this.value.equals(this._effectiveTarget[this._property]);
  52729. }
  52730. else {
  52731. check = this.value === this._effectiveTarget[this._property];
  52732. }
  52733. return this.operator === ValueCondition.IsEqual ? check : !check;
  52734. }
  52735. return false;
  52736. };
  52737. /**
  52738. * Serialize the ValueCondition into a JSON compatible object
  52739. * @returns serialization object
  52740. */
  52741. ValueCondition.prototype.serialize = function () {
  52742. return this._serialize({
  52743. name: "ValueCondition",
  52744. properties: [
  52745. BABYLON.Action._GetTargetProperty(this._target),
  52746. { name: "propertyPath", value: this.propertyPath },
  52747. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  52748. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  52749. ]
  52750. });
  52751. };
  52752. /**
  52753. * Gets the name of the conditional operator for the ValueCondition
  52754. * @param operator the conditional operator
  52755. * @returns the name
  52756. */
  52757. ValueCondition.GetOperatorName = function (operator) {
  52758. switch (operator) {
  52759. case ValueCondition._IsEqual: return "IsEqual";
  52760. case ValueCondition._IsDifferent: return "IsDifferent";
  52761. case ValueCondition._IsGreater: return "IsGreater";
  52762. case ValueCondition._IsLesser: return "IsLesser";
  52763. default: return "";
  52764. }
  52765. };
  52766. /**
  52767. * Internal only
  52768. * @hidden
  52769. */
  52770. ValueCondition._IsEqual = 0;
  52771. /**
  52772. * Internal only
  52773. * @hidden
  52774. */
  52775. ValueCondition._IsDifferent = 1;
  52776. /**
  52777. * Internal only
  52778. * @hidden
  52779. */
  52780. ValueCondition._IsGreater = 2;
  52781. /**
  52782. * Internal only
  52783. * @hidden
  52784. */
  52785. ValueCondition._IsLesser = 3;
  52786. return ValueCondition;
  52787. }(Condition));
  52788. BABYLON.ValueCondition = ValueCondition;
  52789. /**
  52790. * Defines a predicate condition as an extension of Condition
  52791. */
  52792. var PredicateCondition = /** @class */ (function (_super) {
  52793. __extends(PredicateCondition, _super);
  52794. /**
  52795. * Creates a new PredicateCondition
  52796. * @param actionManager manager for the action the condition applies to
  52797. * @param predicate defines the predicate function used to validate the condition
  52798. */
  52799. function PredicateCondition(actionManager,
  52800. /** defines the predicate function used to validate the condition */
  52801. predicate) {
  52802. var _this = _super.call(this, actionManager) || this;
  52803. _this.predicate = predicate;
  52804. return _this;
  52805. }
  52806. /**
  52807. * @returns the validity of the predicate condition
  52808. */
  52809. PredicateCondition.prototype.isValid = function () {
  52810. return this.predicate();
  52811. };
  52812. return PredicateCondition;
  52813. }(Condition));
  52814. BABYLON.PredicateCondition = PredicateCondition;
  52815. /**
  52816. * Defines a state condition as an extension of Condition
  52817. */
  52818. var StateCondition = /** @class */ (function (_super) {
  52819. __extends(StateCondition, _super);
  52820. /**
  52821. * Creates a new StateCondition
  52822. * @param actionManager manager for the action the condition applies to
  52823. * @param target of the condition
  52824. * @param value to compare with target state
  52825. */
  52826. function StateCondition(actionManager, target, value) {
  52827. var _this = _super.call(this, actionManager) || this;
  52828. _this.value = value;
  52829. _this._target = target;
  52830. return _this;
  52831. }
  52832. /**
  52833. * @returns the validity of the state
  52834. */
  52835. StateCondition.prototype.isValid = function () {
  52836. return this._target.state === this.value;
  52837. };
  52838. /**
  52839. * Serialize the StateCondition into a JSON compatible object
  52840. * @returns serialization object
  52841. */
  52842. StateCondition.prototype.serialize = function () {
  52843. return this._serialize({
  52844. name: "StateCondition",
  52845. properties: [
  52846. BABYLON.Action._GetTargetProperty(this._target),
  52847. { name: "value", value: this.value }
  52848. ]
  52849. });
  52850. };
  52851. return StateCondition;
  52852. }(Condition));
  52853. BABYLON.StateCondition = StateCondition;
  52854. })(BABYLON || (BABYLON = {}));
  52855. //# sourceMappingURL=babylon.condition.js.map
  52856. var BABYLON;
  52857. (function (BABYLON) {
  52858. /**
  52859. * The action to be carried out following a trigger
  52860. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  52861. */
  52862. var Action = /** @class */ (function () {
  52863. /**
  52864. * Creates a new Action
  52865. * @param triggerOptions the trigger, with or without parameters, for the action
  52866. * @param condition an optional determinant of action
  52867. */
  52868. function Action(
  52869. /** the trigger, with or without parameters, for the action */
  52870. triggerOptions, condition) {
  52871. this.triggerOptions = triggerOptions;
  52872. /**
  52873. * An event triggered prior to action being executed.
  52874. */
  52875. this.onBeforeExecuteObservable = new BABYLON.Observable();
  52876. if (triggerOptions.parameter) {
  52877. this.trigger = triggerOptions.trigger;
  52878. this._triggerParameter = triggerOptions.parameter;
  52879. }
  52880. else {
  52881. this.trigger = triggerOptions;
  52882. }
  52883. this._nextActiveAction = this;
  52884. this._condition = condition;
  52885. }
  52886. /**
  52887. * Internal only
  52888. * @hidden
  52889. */
  52890. Action.prototype._prepare = function () {
  52891. };
  52892. /**
  52893. * Gets the trigger parameters
  52894. * @returns the trigger parameters
  52895. */
  52896. Action.prototype.getTriggerParameter = function () {
  52897. return this._triggerParameter;
  52898. };
  52899. /**
  52900. * Internal only - executes current action event
  52901. * @hidden
  52902. */
  52903. Action.prototype._executeCurrent = function (evt) {
  52904. if (this._nextActiveAction._condition) {
  52905. var condition = this._nextActiveAction._condition;
  52906. var currentRenderId = this._actionManager.getScene().getRenderId();
  52907. // We cache the current evaluation for the current frame
  52908. if (condition._evaluationId === currentRenderId) {
  52909. if (!condition._currentResult) {
  52910. return;
  52911. }
  52912. }
  52913. else {
  52914. condition._evaluationId = currentRenderId;
  52915. if (!condition.isValid()) {
  52916. condition._currentResult = false;
  52917. return;
  52918. }
  52919. condition._currentResult = true;
  52920. }
  52921. }
  52922. this.onBeforeExecuteObservable.notifyObservers(this);
  52923. this._nextActiveAction.execute(evt);
  52924. this.skipToNextActiveAction();
  52925. };
  52926. /**
  52927. * Execute placeholder for child classes
  52928. * @param evt optional action event
  52929. */
  52930. Action.prototype.execute = function (evt) {
  52931. };
  52932. /**
  52933. * Skips to next active action
  52934. */
  52935. Action.prototype.skipToNextActiveAction = function () {
  52936. if (this._nextActiveAction._child) {
  52937. if (!this._nextActiveAction._child._actionManager) {
  52938. this._nextActiveAction._child._actionManager = this._actionManager;
  52939. }
  52940. this._nextActiveAction = this._nextActiveAction._child;
  52941. }
  52942. else {
  52943. this._nextActiveAction = this;
  52944. }
  52945. };
  52946. /**
  52947. * Adds action to chain of actions, may be a DoNothingAction
  52948. * @param action defines the next action to execute
  52949. * @returns The action passed in
  52950. * @see https://www.babylonjs-playground.com/#1T30HR#0
  52951. */
  52952. Action.prototype.then = function (action) {
  52953. this._child = action;
  52954. action._actionManager = this._actionManager;
  52955. action._prepare();
  52956. return action;
  52957. };
  52958. /**
  52959. * Internal only
  52960. * @hidden
  52961. */
  52962. Action.prototype._getProperty = function (propertyPath) {
  52963. return this._actionManager._getProperty(propertyPath);
  52964. };
  52965. /**
  52966. * Internal only
  52967. * @hidden
  52968. */
  52969. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  52970. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52971. };
  52972. /**
  52973. * Serialize placeholder for child classes
  52974. * @param parent of child
  52975. * @returns the serialized object
  52976. */
  52977. Action.prototype.serialize = function (parent) {
  52978. };
  52979. /**
  52980. * Internal only called by serialize
  52981. * @hidden
  52982. */
  52983. Action.prototype._serialize = function (serializedAction, parent) {
  52984. var serializationObject = {
  52985. type: 1,
  52986. children: [],
  52987. name: serializedAction.name,
  52988. properties: serializedAction.properties || []
  52989. };
  52990. // Serialize child
  52991. if (this._child) {
  52992. this._child.serialize(serializationObject);
  52993. }
  52994. // Check if "this" has a condition
  52995. if (this._condition) {
  52996. var serializedCondition = this._condition.serialize();
  52997. serializedCondition.children.push(serializationObject);
  52998. if (parent) {
  52999. parent.children.push(serializedCondition);
  53000. }
  53001. return serializedCondition;
  53002. }
  53003. if (parent) {
  53004. parent.children.push(serializationObject);
  53005. }
  53006. return serializationObject;
  53007. };
  53008. /**
  53009. * Internal only
  53010. * @hidden
  53011. */
  53012. Action._SerializeValueAsString = function (value) {
  53013. if (typeof value === "number") {
  53014. return value.toString();
  53015. }
  53016. if (typeof value === "boolean") {
  53017. return value ? "true" : "false";
  53018. }
  53019. if (value instanceof BABYLON.Vector2) {
  53020. return value.x + ", " + value.y;
  53021. }
  53022. if (value instanceof BABYLON.Vector3) {
  53023. return value.x + ", " + value.y + ", " + value.z;
  53024. }
  53025. if (value instanceof BABYLON.Color3) {
  53026. return value.r + ", " + value.g + ", " + value.b;
  53027. }
  53028. if (value instanceof BABYLON.Color4) {
  53029. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  53030. }
  53031. return value; // string
  53032. };
  53033. /**
  53034. * Internal only
  53035. * @hidden
  53036. */
  53037. Action._GetTargetProperty = function (target) {
  53038. return {
  53039. name: "target",
  53040. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  53041. : target instanceof BABYLON.Light ? "LightProperties"
  53042. : target instanceof BABYLON.Camera ? "CameraProperties"
  53043. : "SceneProperties",
  53044. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  53045. };
  53046. };
  53047. return Action;
  53048. }());
  53049. BABYLON.Action = Action;
  53050. })(BABYLON || (BABYLON = {}));
  53051. //# sourceMappingURL=babylon.action.js.map
  53052. var BABYLON;
  53053. (function (BABYLON) {
  53054. /**
  53055. * ActionEvent is the event being sent when an action is triggered.
  53056. */
  53057. var ActionEvent = /** @class */ (function () {
  53058. /**
  53059. * Creates a new ActionEvent
  53060. * @param source The mesh or sprite that triggered the action
  53061. * @param pointerX The X mouse cursor position at the time of the event
  53062. * @param pointerY The Y mouse cursor position at the time of the event
  53063. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  53064. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  53065. * @param additionalData additional data for the event
  53066. */
  53067. function ActionEvent(
  53068. /** The mesh or sprite that triggered the action */
  53069. source,
  53070. /** The X mouse cursor position at the time of the event */
  53071. pointerX,
  53072. /** The Y mouse cursor position at the time of the event */
  53073. pointerY,
  53074. /** The mesh that is currently pointed at (can be null) */
  53075. meshUnderPointer,
  53076. /** the original (browser) event that triggered the ActionEvent */
  53077. sourceEvent,
  53078. /** additional data for the event */
  53079. additionalData) {
  53080. this.source = source;
  53081. this.pointerX = pointerX;
  53082. this.pointerY = pointerY;
  53083. this.meshUnderPointer = meshUnderPointer;
  53084. this.sourceEvent = sourceEvent;
  53085. this.additionalData = additionalData;
  53086. }
  53087. /**
  53088. * Helper function to auto-create an ActionEvent from a source mesh.
  53089. * @param source The source mesh that triggered the event
  53090. * @param evt The original (browser) event
  53091. * @param additionalData additional data for the event
  53092. * @returns the new ActionEvent
  53093. */
  53094. ActionEvent.CreateNew = function (source, evt, additionalData) {
  53095. var scene = source.getScene();
  53096. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  53097. };
  53098. /**
  53099. * Helper function to auto-create an ActionEvent from a source sprite
  53100. * @param source The source sprite that triggered the event
  53101. * @param scene Scene associated with the sprite
  53102. * @param evt The original (browser) event
  53103. * @param additionalData additional data for the event
  53104. * @returns the new ActionEvent
  53105. */
  53106. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  53107. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  53108. };
  53109. /**
  53110. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  53111. * @param scene the scene where the event occurred
  53112. * @param evt The original (browser) event
  53113. * @returns the new ActionEvent
  53114. */
  53115. ActionEvent.CreateNewFromScene = function (scene, evt) {
  53116. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  53117. };
  53118. /**
  53119. * Helper function to auto-create an ActionEvent from a primitive
  53120. * @param prim defines the target primitive
  53121. * @param pointerPos defines the pointer position
  53122. * @param evt The original (browser) event
  53123. * @param additionalData additional data for the event
  53124. * @returns the new ActionEvent
  53125. */
  53126. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  53127. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  53128. };
  53129. return ActionEvent;
  53130. }());
  53131. BABYLON.ActionEvent = ActionEvent;
  53132. /**
  53133. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  53134. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  53135. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  53136. */
  53137. var ActionManager = /** @class */ (function () {
  53138. /**
  53139. * Creates a new action manager
  53140. * @param scene defines the hosting scene
  53141. */
  53142. function ActionManager(scene) {
  53143. // Members
  53144. /** Gets the list of actions */
  53145. this.actions = new Array();
  53146. /** Gets the cursor to use when hovering items */
  53147. this.hoverCursor = '';
  53148. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  53149. scene._actionManagers.push(this);
  53150. }
  53151. Object.defineProperty(ActionManager, "NothingTrigger", {
  53152. /**
  53153. * Nothing
  53154. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53155. */
  53156. get: function () {
  53157. return ActionManager._NothingTrigger;
  53158. },
  53159. enumerable: true,
  53160. configurable: true
  53161. });
  53162. Object.defineProperty(ActionManager, "OnPickTrigger", {
  53163. /**
  53164. * On pick
  53165. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53166. */
  53167. get: function () {
  53168. return ActionManager._OnPickTrigger;
  53169. },
  53170. enumerable: true,
  53171. configurable: true
  53172. });
  53173. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  53174. /**
  53175. * On left pick
  53176. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53177. */
  53178. get: function () {
  53179. return ActionManager._OnLeftPickTrigger;
  53180. },
  53181. enumerable: true,
  53182. configurable: true
  53183. });
  53184. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  53185. /**
  53186. * On right pick
  53187. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53188. */
  53189. get: function () {
  53190. return ActionManager._OnRightPickTrigger;
  53191. },
  53192. enumerable: true,
  53193. configurable: true
  53194. });
  53195. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  53196. /**
  53197. * On center pick
  53198. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53199. */
  53200. get: function () {
  53201. return ActionManager._OnCenterPickTrigger;
  53202. },
  53203. enumerable: true,
  53204. configurable: true
  53205. });
  53206. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  53207. /**
  53208. * On pick down
  53209. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53210. */
  53211. get: function () {
  53212. return ActionManager._OnPickDownTrigger;
  53213. },
  53214. enumerable: true,
  53215. configurable: true
  53216. });
  53217. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  53218. /**
  53219. * On double pick
  53220. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53221. */
  53222. get: function () {
  53223. return ActionManager._OnDoublePickTrigger;
  53224. },
  53225. enumerable: true,
  53226. configurable: true
  53227. });
  53228. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  53229. /**
  53230. * On pick up
  53231. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53232. */
  53233. get: function () {
  53234. return ActionManager._OnPickUpTrigger;
  53235. },
  53236. enumerable: true,
  53237. configurable: true
  53238. });
  53239. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  53240. /**
  53241. * On pick out.
  53242. * This trigger will only be raised if you also declared a OnPickDown
  53243. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53244. */
  53245. get: function () {
  53246. return ActionManager._OnPickOutTrigger;
  53247. },
  53248. enumerable: true,
  53249. configurable: true
  53250. });
  53251. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  53252. /**
  53253. * On long press
  53254. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53255. */
  53256. get: function () {
  53257. return ActionManager._OnLongPressTrigger;
  53258. },
  53259. enumerable: true,
  53260. configurable: true
  53261. });
  53262. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  53263. /**
  53264. * On pointer over
  53265. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53266. */
  53267. get: function () {
  53268. return ActionManager._OnPointerOverTrigger;
  53269. },
  53270. enumerable: true,
  53271. configurable: true
  53272. });
  53273. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  53274. /**
  53275. * On pointer out
  53276. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53277. */
  53278. get: function () {
  53279. return ActionManager._OnPointerOutTrigger;
  53280. },
  53281. enumerable: true,
  53282. configurable: true
  53283. });
  53284. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  53285. /**
  53286. * On every frame
  53287. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53288. */
  53289. get: function () {
  53290. return ActionManager._OnEveryFrameTrigger;
  53291. },
  53292. enumerable: true,
  53293. configurable: true
  53294. });
  53295. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  53296. /**
  53297. * On intersection enter
  53298. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53299. */
  53300. get: function () {
  53301. return ActionManager._OnIntersectionEnterTrigger;
  53302. },
  53303. enumerable: true,
  53304. configurable: true
  53305. });
  53306. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  53307. /**
  53308. * On intersection exit
  53309. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53310. */
  53311. get: function () {
  53312. return ActionManager._OnIntersectionExitTrigger;
  53313. },
  53314. enumerable: true,
  53315. configurable: true
  53316. });
  53317. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  53318. /**
  53319. * On key down
  53320. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53321. */
  53322. get: function () {
  53323. return ActionManager._OnKeyDownTrigger;
  53324. },
  53325. enumerable: true,
  53326. configurable: true
  53327. });
  53328. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  53329. /**
  53330. * On key up
  53331. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53332. */
  53333. get: function () {
  53334. return ActionManager._OnKeyUpTrigger;
  53335. },
  53336. enumerable: true,
  53337. configurable: true
  53338. });
  53339. // Methods
  53340. /**
  53341. * Releases all associated resources
  53342. */
  53343. ActionManager.prototype.dispose = function () {
  53344. var index = this._scene._actionManagers.indexOf(this);
  53345. for (var i = 0; i < this.actions.length; i++) {
  53346. var action = this.actions[i];
  53347. ActionManager.Triggers[action.trigger]--;
  53348. if (ActionManager.Triggers[action.trigger] === 0) {
  53349. delete ActionManager.Triggers[action.trigger];
  53350. }
  53351. }
  53352. if (index > -1) {
  53353. this._scene._actionManagers.splice(index, 1);
  53354. }
  53355. };
  53356. /**
  53357. * Gets hosting scene
  53358. * @returns the hosting scene
  53359. */
  53360. ActionManager.prototype.getScene = function () {
  53361. return this._scene;
  53362. };
  53363. /**
  53364. * Does this action manager handles actions of any of the given triggers
  53365. * @param triggers defines the triggers to be tested
  53366. * @return a boolean indicating whether one (or more) of the triggers is handled
  53367. */
  53368. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  53369. for (var index = 0; index < this.actions.length; index++) {
  53370. var action = this.actions[index];
  53371. if (triggers.indexOf(action.trigger) > -1) {
  53372. return true;
  53373. }
  53374. }
  53375. return false;
  53376. };
  53377. /**
  53378. * Does this action manager handles actions of a given trigger
  53379. * @param trigger defines the trigger to be tested
  53380. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  53381. * @return whether the trigger is handled
  53382. */
  53383. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  53384. for (var index = 0; index < this.actions.length; index++) {
  53385. var action = this.actions[index];
  53386. if (action.trigger === trigger) {
  53387. if (parameterPredicate) {
  53388. if (parameterPredicate(action.getTriggerParameter())) {
  53389. return true;
  53390. }
  53391. }
  53392. else {
  53393. return true;
  53394. }
  53395. }
  53396. }
  53397. return false;
  53398. };
  53399. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  53400. /**
  53401. * Does this action manager has pointer triggers
  53402. */
  53403. get: function () {
  53404. for (var index = 0; index < this.actions.length; index++) {
  53405. var action = this.actions[index];
  53406. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  53407. return true;
  53408. }
  53409. }
  53410. return false;
  53411. },
  53412. enumerable: true,
  53413. configurable: true
  53414. });
  53415. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  53416. /**
  53417. * Does this action manager has pick triggers
  53418. */
  53419. get: function () {
  53420. for (var index = 0; index < this.actions.length; index++) {
  53421. var action = this.actions[index];
  53422. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  53423. return true;
  53424. }
  53425. }
  53426. return false;
  53427. },
  53428. enumerable: true,
  53429. configurable: true
  53430. });
  53431. Object.defineProperty(ActionManager, "HasTriggers", {
  53432. /**
  53433. * Does exist one action manager with at least one trigger
  53434. **/
  53435. get: function () {
  53436. for (var t in ActionManager.Triggers) {
  53437. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53438. return true;
  53439. }
  53440. }
  53441. return false;
  53442. },
  53443. enumerable: true,
  53444. configurable: true
  53445. });
  53446. Object.defineProperty(ActionManager, "HasPickTriggers", {
  53447. /**
  53448. * Does exist one action manager with at least one pick trigger
  53449. **/
  53450. get: function () {
  53451. for (var t in ActionManager.Triggers) {
  53452. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53453. var t_int = parseInt(t);
  53454. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  53455. return true;
  53456. }
  53457. }
  53458. }
  53459. return false;
  53460. },
  53461. enumerable: true,
  53462. configurable: true
  53463. });
  53464. /**
  53465. * Does exist one action manager that handles actions of a given trigger
  53466. * @param trigger defines the trigger to be tested
  53467. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  53468. **/
  53469. ActionManager.HasSpecificTrigger = function (trigger) {
  53470. for (var t in ActionManager.Triggers) {
  53471. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53472. var t_int = parseInt(t);
  53473. if (t_int === trigger) {
  53474. return true;
  53475. }
  53476. }
  53477. }
  53478. return false;
  53479. };
  53480. /**
  53481. * Registers an action to this action manager
  53482. * @param action defines the action to be registered
  53483. * @return the action amended (prepared) after registration
  53484. */
  53485. ActionManager.prototype.registerAction = function (action) {
  53486. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  53487. if (this.getScene().actionManager !== this) {
  53488. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  53489. return null;
  53490. }
  53491. }
  53492. this.actions.push(action);
  53493. if (ActionManager.Triggers[action.trigger]) {
  53494. ActionManager.Triggers[action.trigger]++;
  53495. }
  53496. else {
  53497. ActionManager.Triggers[action.trigger] = 1;
  53498. }
  53499. action._actionManager = this;
  53500. action._prepare();
  53501. return action;
  53502. };
  53503. /**
  53504. * Unregisters an action to this action manager
  53505. * @param action defines the action to be unregistered
  53506. * @return a boolean indicating whether the action has been unregistered
  53507. */
  53508. ActionManager.prototype.unregisterAction = function (action) {
  53509. var index = this.actions.indexOf(action);
  53510. if (index !== -1) {
  53511. this.actions.splice(index, 1);
  53512. ActionManager.Triggers[action.trigger] -= 1;
  53513. if (ActionManager.Triggers[action.trigger] === 0) {
  53514. delete ActionManager.Triggers[action.trigger];
  53515. }
  53516. delete action._actionManager;
  53517. return true;
  53518. }
  53519. return false;
  53520. };
  53521. /**
  53522. * Process a specific trigger
  53523. * @param trigger defines the trigger to process
  53524. * @param evt defines the event details to be processed
  53525. */
  53526. ActionManager.prototype.processTrigger = function (trigger, evt) {
  53527. for (var index = 0; index < this.actions.length; index++) {
  53528. var action = this.actions[index];
  53529. if (action.trigger === trigger) {
  53530. if (evt) {
  53531. if (trigger === ActionManager.OnKeyUpTrigger
  53532. || trigger === ActionManager.OnKeyDownTrigger) {
  53533. var parameter = action.getTriggerParameter();
  53534. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  53535. if (!parameter.toLowerCase) {
  53536. continue;
  53537. }
  53538. var lowerCase = parameter.toLowerCase();
  53539. if (lowerCase !== evt.sourceEvent.key) {
  53540. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  53541. var actualkey = String.fromCharCode(unicode).toLowerCase();
  53542. if (actualkey !== lowerCase) {
  53543. continue;
  53544. }
  53545. }
  53546. }
  53547. }
  53548. }
  53549. action._executeCurrent(evt);
  53550. }
  53551. }
  53552. };
  53553. /** @hidden */
  53554. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  53555. var properties = propertyPath.split(".");
  53556. for (var index = 0; index < properties.length - 1; index++) {
  53557. target = target[properties[index]];
  53558. }
  53559. return target;
  53560. };
  53561. /** @hidden */
  53562. ActionManager.prototype._getProperty = function (propertyPath) {
  53563. var properties = propertyPath.split(".");
  53564. return properties[properties.length - 1];
  53565. };
  53566. /**
  53567. * Serialize this manager to a JSON object
  53568. * @param name defines the property name to store this manager
  53569. * @returns a JSON representation of this manager
  53570. */
  53571. ActionManager.prototype.serialize = function (name) {
  53572. var root = {
  53573. children: new Array(),
  53574. name: name,
  53575. type: 3,
  53576. properties: new Array() // Empty for root but required
  53577. };
  53578. for (var i = 0; i < this.actions.length; i++) {
  53579. var triggerObject = {
  53580. type: 0,
  53581. children: new Array(),
  53582. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  53583. properties: new Array()
  53584. };
  53585. var triggerOptions = this.actions[i].triggerOptions;
  53586. if (triggerOptions && typeof triggerOptions !== "number") {
  53587. if (triggerOptions.parameter instanceof BABYLON.Node) {
  53588. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  53589. }
  53590. else {
  53591. var parameter = {};
  53592. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  53593. if (triggerOptions.parameter.mesh) {
  53594. parameter._meshId = triggerOptions.parameter.mesh.id;
  53595. }
  53596. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  53597. }
  53598. }
  53599. // Serialize child action, recursively
  53600. this.actions[i].serialize(triggerObject);
  53601. // Add serialized trigger
  53602. root.children.push(triggerObject);
  53603. }
  53604. return root;
  53605. };
  53606. /**
  53607. * Creates a new ActionManager from a JSON data
  53608. * @param parsedActions defines the JSON data to read from
  53609. * @param object defines the hosting mesh
  53610. * @param scene defines the hosting scene
  53611. */
  53612. ActionManager.Parse = function (parsedActions, object, scene) {
  53613. var actionManager = new ActionManager(scene);
  53614. if (object === null)
  53615. scene.actionManager = actionManager;
  53616. else
  53617. object.actionManager = actionManager;
  53618. // instanciate a new object
  53619. var instanciate = function (name, params) {
  53620. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  53621. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  53622. newInstance.constructor.apply(newInstance, params);
  53623. return newInstance;
  53624. };
  53625. var parseParameter = function (name, value, target, propertyPath) {
  53626. if (propertyPath === null) {
  53627. // String, boolean or float
  53628. var floatValue = parseFloat(value);
  53629. if (value === "true" || value === "false")
  53630. return value === "true";
  53631. else
  53632. return isNaN(floatValue) ? value : floatValue;
  53633. }
  53634. var effectiveTarget = propertyPath.split(".");
  53635. var values = value.split(",");
  53636. // Get effective Target
  53637. for (var i = 0; i < effectiveTarget.length; i++) {
  53638. target = target[effectiveTarget[i]];
  53639. }
  53640. // Return appropriate value with its type
  53641. if (typeof (target) === "boolean")
  53642. return values[0] === "true";
  53643. if (typeof (target) === "string")
  53644. return values[0];
  53645. // Parameters with multiple values such as Vector3 etc.
  53646. var split = new Array();
  53647. for (var i = 0; i < values.length; i++)
  53648. split.push(parseFloat(values[i]));
  53649. if (target instanceof BABYLON.Vector3)
  53650. return BABYLON.Vector3.FromArray(split);
  53651. if (target instanceof BABYLON.Vector4)
  53652. return BABYLON.Vector4.FromArray(split);
  53653. if (target instanceof BABYLON.Color3)
  53654. return BABYLON.Color3.FromArray(split);
  53655. if (target instanceof BABYLON.Color4)
  53656. return BABYLON.Color4.FromArray(split);
  53657. return parseFloat(values[0]);
  53658. };
  53659. // traverse graph per trigger
  53660. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  53661. if (combineArray === void 0) { combineArray = null; }
  53662. if (parsedAction.detached)
  53663. return;
  53664. var parameters = new Array();
  53665. var target = null;
  53666. var propertyPath = null;
  53667. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  53668. // Parameters
  53669. if (parsedAction.type === 2)
  53670. parameters.push(actionManager);
  53671. else
  53672. parameters.push(trigger);
  53673. if (combine) {
  53674. var actions = new Array();
  53675. for (var j = 0; j < parsedAction.combine.length; j++) {
  53676. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  53677. }
  53678. parameters.push(actions);
  53679. }
  53680. else {
  53681. for (var i = 0; i < parsedAction.properties.length; i++) {
  53682. var value = parsedAction.properties[i].value;
  53683. var name = parsedAction.properties[i].name;
  53684. var targetType = parsedAction.properties[i].targetType;
  53685. if (name === "target")
  53686. if (targetType !== null && targetType === "SceneProperties")
  53687. value = target = scene;
  53688. else
  53689. value = target = scene.getNodeByName(value);
  53690. else if (name === "parent")
  53691. value = scene.getNodeByName(value);
  53692. else if (name === "sound")
  53693. value = scene.getSoundByName(value);
  53694. else if (name !== "propertyPath") {
  53695. if (parsedAction.type === 2 && name === "operator")
  53696. value = BABYLON.ValueCondition[value];
  53697. else
  53698. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  53699. }
  53700. else {
  53701. propertyPath = value;
  53702. }
  53703. parameters.push(value);
  53704. }
  53705. }
  53706. if (combineArray === null) {
  53707. parameters.push(condition);
  53708. }
  53709. else {
  53710. parameters.push(null);
  53711. }
  53712. // If interpolate value action
  53713. if (parsedAction.name === "InterpolateValueAction") {
  53714. var param = parameters[parameters.length - 2];
  53715. parameters[parameters.length - 1] = param;
  53716. parameters[parameters.length - 2] = condition;
  53717. }
  53718. // Action or condition(s) and not CombineAction
  53719. var newAction = instanciate(parsedAction.name, parameters);
  53720. if (newAction instanceof BABYLON.Condition && condition !== null) {
  53721. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  53722. if (action)
  53723. action.then(nothing);
  53724. else
  53725. actionManager.registerAction(nothing);
  53726. action = nothing;
  53727. }
  53728. if (combineArray === null) {
  53729. if (newAction instanceof BABYLON.Condition) {
  53730. condition = newAction;
  53731. newAction = action;
  53732. }
  53733. else {
  53734. condition = null;
  53735. if (action)
  53736. action.then(newAction);
  53737. else
  53738. actionManager.registerAction(newAction);
  53739. }
  53740. }
  53741. else {
  53742. combineArray.push(newAction);
  53743. }
  53744. for (var i = 0; i < parsedAction.children.length; i++)
  53745. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  53746. };
  53747. // triggers
  53748. for (var i = 0; i < parsedActions.children.length; i++) {
  53749. var triggerParams;
  53750. var trigger = parsedActions.children[i];
  53751. if (trigger.properties.length > 0) {
  53752. var param = trigger.properties[0].value;
  53753. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  53754. if (value._meshId) {
  53755. value.mesh = scene.getMeshByID(value._meshId);
  53756. }
  53757. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  53758. }
  53759. else
  53760. triggerParams = ActionManager[trigger.name];
  53761. for (var j = 0; j < trigger.children.length; j++) {
  53762. if (!trigger.detached)
  53763. traverse(trigger.children[j], triggerParams, null, null);
  53764. }
  53765. }
  53766. };
  53767. /**
  53768. * Get a trigger name by index
  53769. * @param trigger defines the trigger index
  53770. * @returns a trigger name
  53771. */
  53772. ActionManager.GetTriggerName = function (trigger) {
  53773. switch (trigger) {
  53774. case 0: return "NothingTrigger";
  53775. case 1: return "OnPickTrigger";
  53776. case 2: return "OnLeftPickTrigger";
  53777. case 3: return "OnRightPickTrigger";
  53778. case 4: return "OnCenterPickTrigger";
  53779. case 5: return "OnPickDownTrigger";
  53780. case 6: return "OnPickUpTrigger";
  53781. case 7: return "OnLongPressTrigger";
  53782. case 8: return "OnPointerOverTrigger";
  53783. case 9: return "OnPointerOutTrigger";
  53784. case 10: return "OnEveryFrameTrigger";
  53785. case 11: return "OnIntersectionEnterTrigger";
  53786. case 12: return "OnIntersectionExitTrigger";
  53787. case 13: return "OnKeyDownTrigger";
  53788. case 14: return "OnKeyUpTrigger";
  53789. case 15: return "OnPickOutTrigger";
  53790. default: return "";
  53791. }
  53792. };
  53793. // Statics
  53794. ActionManager._NothingTrigger = 0;
  53795. ActionManager._OnPickTrigger = 1;
  53796. ActionManager._OnLeftPickTrigger = 2;
  53797. ActionManager._OnRightPickTrigger = 3;
  53798. ActionManager._OnCenterPickTrigger = 4;
  53799. ActionManager._OnPickDownTrigger = 5;
  53800. ActionManager._OnDoublePickTrigger = 6;
  53801. ActionManager._OnPickUpTrigger = 7;
  53802. ActionManager._OnLongPressTrigger = 8;
  53803. ActionManager._OnPointerOverTrigger = 9;
  53804. ActionManager._OnPointerOutTrigger = 10;
  53805. ActionManager._OnEveryFrameTrigger = 11;
  53806. ActionManager._OnIntersectionEnterTrigger = 12;
  53807. ActionManager._OnIntersectionExitTrigger = 13;
  53808. ActionManager._OnKeyDownTrigger = 14;
  53809. ActionManager._OnKeyUpTrigger = 15;
  53810. ActionManager._OnPickOutTrigger = 16;
  53811. /** Gets the list of active triggers */
  53812. ActionManager.Triggers = {};
  53813. return ActionManager;
  53814. }());
  53815. BABYLON.ActionManager = ActionManager;
  53816. })(BABYLON || (BABYLON = {}));
  53817. //# sourceMappingURL=babylon.actionManager.js.map
  53818. var BABYLON;
  53819. (function (BABYLON) {
  53820. var InterpolateValueAction = /** @class */ (function (_super) {
  53821. __extends(InterpolateValueAction, _super);
  53822. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  53823. if (duration === void 0) { duration = 1000; }
  53824. var _this = _super.call(this, triggerOptions, condition) || this;
  53825. _this.propertyPath = propertyPath;
  53826. _this.value = value;
  53827. _this.duration = duration;
  53828. _this.stopOtherAnimations = stopOtherAnimations;
  53829. _this.onInterpolationDone = onInterpolationDone;
  53830. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  53831. _this._target = _this._effectiveTarget = target;
  53832. return _this;
  53833. }
  53834. InterpolateValueAction.prototype._prepare = function () {
  53835. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53836. this._property = this._getProperty(this.propertyPath);
  53837. };
  53838. InterpolateValueAction.prototype.execute = function () {
  53839. var _this = this;
  53840. var scene = this._actionManager.getScene();
  53841. var keys = [
  53842. {
  53843. frame: 0,
  53844. value: this._effectiveTarget[this._property]
  53845. }, {
  53846. frame: 100,
  53847. value: this.value
  53848. }
  53849. ];
  53850. var dataType;
  53851. if (typeof this.value === "number") {
  53852. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  53853. }
  53854. else if (this.value instanceof BABYLON.Color3) {
  53855. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  53856. }
  53857. else if (this.value instanceof BABYLON.Vector3) {
  53858. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  53859. }
  53860. else if (this.value instanceof BABYLON.Matrix) {
  53861. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  53862. }
  53863. else if (this.value instanceof BABYLON.Quaternion) {
  53864. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  53865. }
  53866. else {
  53867. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  53868. return;
  53869. }
  53870. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  53871. animation.setKeys(keys);
  53872. if (this.stopOtherAnimations) {
  53873. scene.stopAnimation(this._effectiveTarget);
  53874. }
  53875. var wrapper = function () {
  53876. _this.onInterpolationDoneObservable.notifyObservers(_this);
  53877. if (_this.onInterpolationDone) {
  53878. _this.onInterpolationDone();
  53879. }
  53880. };
  53881. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  53882. };
  53883. InterpolateValueAction.prototype.serialize = function (parent) {
  53884. return _super.prototype._serialize.call(this, {
  53885. name: "InterpolateValueAction",
  53886. properties: [
  53887. BABYLON.Action._GetTargetProperty(this._target),
  53888. { name: "propertyPath", value: this.propertyPath },
  53889. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53890. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  53891. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  53892. ]
  53893. }, parent);
  53894. };
  53895. return InterpolateValueAction;
  53896. }(BABYLON.Action));
  53897. BABYLON.InterpolateValueAction = InterpolateValueAction;
  53898. })(BABYLON || (BABYLON = {}));
  53899. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  53900. var BABYLON;
  53901. (function (BABYLON) {
  53902. var SwitchBooleanAction = /** @class */ (function (_super) {
  53903. __extends(SwitchBooleanAction, _super);
  53904. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  53905. var _this = _super.call(this, triggerOptions, condition) || this;
  53906. _this.propertyPath = propertyPath;
  53907. _this._target = _this._effectiveTarget = target;
  53908. return _this;
  53909. }
  53910. SwitchBooleanAction.prototype._prepare = function () {
  53911. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53912. this._property = this._getProperty(this.propertyPath);
  53913. };
  53914. SwitchBooleanAction.prototype.execute = function () {
  53915. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  53916. };
  53917. SwitchBooleanAction.prototype.serialize = function (parent) {
  53918. return _super.prototype._serialize.call(this, {
  53919. name: "SwitchBooleanAction",
  53920. properties: [
  53921. BABYLON.Action._GetTargetProperty(this._target),
  53922. { name: "propertyPath", value: this.propertyPath }
  53923. ]
  53924. }, parent);
  53925. };
  53926. return SwitchBooleanAction;
  53927. }(BABYLON.Action));
  53928. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  53929. var SetStateAction = /** @class */ (function (_super) {
  53930. __extends(SetStateAction, _super);
  53931. function SetStateAction(triggerOptions, target, value, condition) {
  53932. var _this = _super.call(this, triggerOptions, condition) || this;
  53933. _this.value = value;
  53934. _this._target = target;
  53935. return _this;
  53936. }
  53937. SetStateAction.prototype.execute = function () {
  53938. this._target.state = this.value;
  53939. };
  53940. SetStateAction.prototype.serialize = function (parent) {
  53941. return _super.prototype._serialize.call(this, {
  53942. name: "SetStateAction",
  53943. properties: [
  53944. BABYLON.Action._GetTargetProperty(this._target),
  53945. { name: "value", value: this.value }
  53946. ]
  53947. }, parent);
  53948. };
  53949. return SetStateAction;
  53950. }(BABYLON.Action));
  53951. BABYLON.SetStateAction = SetStateAction;
  53952. var SetValueAction = /** @class */ (function (_super) {
  53953. __extends(SetValueAction, _super);
  53954. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  53955. var _this = _super.call(this, triggerOptions, condition) || this;
  53956. _this.propertyPath = propertyPath;
  53957. _this.value = value;
  53958. _this._target = _this._effectiveTarget = target;
  53959. return _this;
  53960. }
  53961. SetValueAction.prototype._prepare = function () {
  53962. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53963. this._property = this._getProperty(this.propertyPath);
  53964. };
  53965. SetValueAction.prototype.execute = function () {
  53966. this._effectiveTarget[this._property] = this.value;
  53967. if (this._target.markAsDirty) {
  53968. this._target.markAsDirty(this._property);
  53969. }
  53970. };
  53971. SetValueAction.prototype.serialize = function (parent) {
  53972. return _super.prototype._serialize.call(this, {
  53973. name: "SetValueAction",
  53974. properties: [
  53975. BABYLON.Action._GetTargetProperty(this._target),
  53976. { name: "propertyPath", value: this.propertyPath },
  53977. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53978. ]
  53979. }, parent);
  53980. };
  53981. return SetValueAction;
  53982. }(BABYLON.Action));
  53983. BABYLON.SetValueAction = SetValueAction;
  53984. var IncrementValueAction = /** @class */ (function (_super) {
  53985. __extends(IncrementValueAction, _super);
  53986. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  53987. var _this = _super.call(this, triggerOptions, condition) || this;
  53988. _this.propertyPath = propertyPath;
  53989. _this.value = value;
  53990. _this._target = _this._effectiveTarget = target;
  53991. return _this;
  53992. }
  53993. IncrementValueAction.prototype._prepare = function () {
  53994. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53995. this._property = this._getProperty(this.propertyPath);
  53996. if (typeof this._effectiveTarget[this._property] !== "number") {
  53997. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  53998. }
  53999. };
  54000. IncrementValueAction.prototype.execute = function () {
  54001. this._effectiveTarget[this._property] += this.value;
  54002. if (this._target.markAsDirty) {
  54003. this._target.markAsDirty(this._property);
  54004. }
  54005. };
  54006. IncrementValueAction.prototype.serialize = function (parent) {
  54007. return _super.prototype._serialize.call(this, {
  54008. name: "IncrementValueAction",
  54009. properties: [
  54010. BABYLON.Action._GetTargetProperty(this._target),
  54011. { name: "propertyPath", value: this.propertyPath },
  54012. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  54013. ]
  54014. }, parent);
  54015. };
  54016. return IncrementValueAction;
  54017. }(BABYLON.Action));
  54018. BABYLON.IncrementValueAction = IncrementValueAction;
  54019. var PlayAnimationAction = /** @class */ (function (_super) {
  54020. __extends(PlayAnimationAction, _super);
  54021. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  54022. var _this = _super.call(this, triggerOptions, condition) || this;
  54023. _this.from = from;
  54024. _this.to = to;
  54025. _this.loop = loop;
  54026. _this._target = target;
  54027. return _this;
  54028. }
  54029. PlayAnimationAction.prototype._prepare = function () {
  54030. };
  54031. PlayAnimationAction.prototype.execute = function () {
  54032. var scene = this._actionManager.getScene();
  54033. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  54034. };
  54035. PlayAnimationAction.prototype.serialize = function (parent) {
  54036. return _super.prototype._serialize.call(this, {
  54037. name: "PlayAnimationAction",
  54038. properties: [
  54039. BABYLON.Action._GetTargetProperty(this._target),
  54040. { name: "from", value: String(this.from) },
  54041. { name: "to", value: String(this.to) },
  54042. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  54043. ]
  54044. }, parent);
  54045. };
  54046. return PlayAnimationAction;
  54047. }(BABYLON.Action));
  54048. BABYLON.PlayAnimationAction = PlayAnimationAction;
  54049. var StopAnimationAction = /** @class */ (function (_super) {
  54050. __extends(StopAnimationAction, _super);
  54051. function StopAnimationAction(triggerOptions, target, condition) {
  54052. var _this = _super.call(this, triggerOptions, condition) || this;
  54053. _this._target = target;
  54054. return _this;
  54055. }
  54056. StopAnimationAction.prototype._prepare = function () {
  54057. };
  54058. StopAnimationAction.prototype.execute = function () {
  54059. var scene = this._actionManager.getScene();
  54060. scene.stopAnimation(this._target);
  54061. };
  54062. StopAnimationAction.prototype.serialize = function (parent) {
  54063. return _super.prototype._serialize.call(this, {
  54064. name: "StopAnimationAction",
  54065. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  54066. }, parent);
  54067. };
  54068. return StopAnimationAction;
  54069. }(BABYLON.Action));
  54070. BABYLON.StopAnimationAction = StopAnimationAction;
  54071. var DoNothingAction = /** @class */ (function (_super) {
  54072. __extends(DoNothingAction, _super);
  54073. function DoNothingAction(triggerOptions, condition) {
  54074. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  54075. return _super.call(this, triggerOptions, condition) || this;
  54076. }
  54077. DoNothingAction.prototype.execute = function () {
  54078. };
  54079. DoNothingAction.prototype.serialize = function (parent) {
  54080. return _super.prototype._serialize.call(this, {
  54081. name: "DoNothingAction",
  54082. properties: []
  54083. }, parent);
  54084. };
  54085. return DoNothingAction;
  54086. }(BABYLON.Action));
  54087. BABYLON.DoNothingAction = DoNothingAction;
  54088. var CombineAction = /** @class */ (function (_super) {
  54089. __extends(CombineAction, _super);
  54090. function CombineAction(triggerOptions, children, condition) {
  54091. var _this = _super.call(this, triggerOptions, condition) || this;
  54092. _this.children = children;
  54093. return _this;
  54094. }
  54095. CombineAction.prototype._prepare = function () {
  54096. for (var index = 0; index < this.children.length; index++) {
  54097. this.children[index]._actionManager = this._actionManager;
  54098. this.children[index]._prepare();
  54099. }
  54100. };
  54101. CombineAction.prototype.execute = function (evt) {
  54102. for (var index = 0; index < this.children.length; index++) {
  54103. this.children[index].execute(evt);
  54104. }
  54105. };
  54106. CombineAction.prototype.serialize = function (parent) {
  54107. var serializationObject = _super.prototype._serialize.call(this, {
  54108. name: "CombineAction",
  54109. properties: [],
  54110. combine: []
  54111. }, parent);
  54112. for (var i = 0; i < this.children.length; i++) {
  54113. serializationObject.combine.push(this.children[i].serialize(null));
  54114. }
  54115. return serializationObject;
  54116. };
  54117. return CombineAction;
  54118. }(BABYLON.Action));
  54119. BABYLON.CombineAction = CombineAction;
  54120. var ExecuteCodeAction = /** @class */ (function (_super) {
  54121. __extends(ExecuteCodeAction, _super);
  54122. function ExecuteCodeAction(triggerOptions, func, condition) {
  54123. var _this = _super.call(this, triggerOptions, condition) || this;
  54124. _this.func = func;
  54125. return _this;
  54126. }
  54127. ExecuteCodeAction.prototype.execute = function (evt) {
  54128. this.func(evt);
  54129. };
  54130. return ExecuteCodeAction;
  54131. }(BABYLON.Action));
  54132. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  54133. var SetParentAction = /** @class */ (function (_super) {
  54134. __extends(SetParentAction, _super);
  54135. function SetParentAction(triggerOptions, target, parent, condition) {
  54136. var _this = _super.call(this, triggerOptions, condition) || this;
  54137. _this._target = target;
  54138. _this._parent = parent;
  54139. return _this;
  54140. }
  54141. SetParentAction.prototype._prepare = function () {
  54142. };
  54143. SetParentAction.prototype.execute = function () {
  54144. if (this._target.parent === this._parent) {
  54145. return;
  54146. }
  54147. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  54148. invertParentWorldMatrix.invert();
  54149. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  54150. this._target.parent = this._parent;
  54151. };
  54152. SetParentAction.prototype.serialize = function (parent) {
  54153. return _super.prototype._serialize.call(this, {
  54154. name: "SetParentAction",
  54155. properties: [
  54156. BABYLON.Action._GetTargetProperty(this._target),
  54157. BABYLON.Action._GetTargetProperty(this._parent),
  54158. ]
  54159. }, parent);
  54160. };
  54161. return SetParentAction;
  54162. }(BABYLON.Action));
  54163. BABYLON.SetParentAction = SetParentAction;
  54164. var PlaySoundAction = /** @class */ (function (_super) {
  54165. __extends(PlaySoundAction, _super);
  54166. function PlaySoundAction(triggerOptions, sound, condition) {
  54167. var _this = _super.call(this, triggerOptions, condition) || this;
  54168. _this._sound = sound;
  54169. return _this;
  54170. }
  54171. PlaySoundAction.prototype._prepare = function () {
  54172. };
  54173. PlaySoundAction.prototype.execute = function () {
  54174. if (this._sound !== undefined)
  54175. this._sound.play();
  54176. };
  54177. PlaySoundAction.prototype.serialize = function (parent) {
  54178. return _super.prototype._serialize.call(this, {
  54179. name: "PlaySoundAction",
  54180. properties: [{ name: "sound", value: this._sound.name }]
  54181. }, parent);
  54182. };
  54183. return PlaySoundAction;
  54184. }(BABYLON.Action));
  54185. BABYLON.PlaySoundAction = PlaySoundAction;
  54186. var StopSoundAction = /** @class */ (function (_super) {
  54187. __extends(StopSoundAction, _super);
  54188. function StopSoundAction(triggerOptions, sound, condition) {
  54189. var _this = _super.call(this, triggerOptions, condition) || this;
  54190. _this._sound = sound;
  54191. return _this;
  54192. }
  54193. StopSoundAction.prototype._prepare = function () {
  54194. };
  54195. StopSoundAction.prototype.execute = function () {
  54196. if (this._sound !== undefined)
  54197. this._sound.stop();
  54198. };
  54199. StopSoundAction.prototype.serialize = function (parent) {
  54200. return _super.prototype._serialize.call(this, {
  54201. name: "StopSoundAction",
  54202. properties: [{ name: "sound", value: this._sound.name }]
  54203. }, parent);
  54204. };
  54205. return StopSoundAction;
  54206. }(BABYLON.Action));
  54207. BABYLON.StopSoundAction = StopSoundAction;
  54208. })(BABYLON || (BABYLON = {}));
  54209. //# sourceMappingURL=babylon.directActions.js.map
  54210. var BABYLON;
  54211. (function (BABYLON) {
  54212. var SpriteManager = /** @class */ (function () {
  54213. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  54214. if (epsilon === void 0) { epsilon = 0.01; }
  54215. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54216. this.name = name;
  54217. this.sprites = new Array();
  54218. this.renderingGroupId = 0;
  54219. this.layerMask = 0x0FFFFFFF;
  54220. this.fogEnabled = true;
  54221. this.isPickable = false;
  54222. /**
  54223. * An event triggered when the manager is disposed.
  54224. */
  54225. this.onDisposeObservable = new BABYLON.Observable();
  54226. this._vertexBuffers = {};
  54227. this._capacity = capacity;
  54228. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  54229. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54230. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54231. if (cellSize.width && cellSize.height) {
  54232. this.cellWidth = cellSize.width;
  54233. this.cellHeight = cellSize.height;
  54234. }
  54235. else if (cellSize !== undefined) {
  54236. this.cellWidth = cellSize;
  54237. this.cellHeight = cellSize;
  54238. }
  54239. else {
  54240. return;
  54241. }
  54242. this._epsilon = epsilon;
  54243. this._scene = scene;
  54244. this._scene.spriteManagers.push(this);
  54245. var indices = [];
  54246. var index = 0;
  54247. for (var count = 0; count < capacity; count++) {
  54248. indices.push(index);
  54249. indices.push(index + 1);
  54250. indices.push(index + 2);
  54251. indices.push(index);
  54252. indices.push(index + 2);
  54253. indices.push(index + 3);
  54254. index += 4;
  54255. }
  54256. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  54257. // VBO
  54258. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  54259. this._vertexData = new Float32Array(capacity * 16 * 4);
  54260. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  54261. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  54262. var options = this._buffer.createVertexBuffer("options", 4, 4);
  54263. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  54264. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  54265. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  54266. this._vertexBuffers["options"] = options;
  54267. this._vertexBuffers["cellInfo"] = cellInfo;
  54268. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  54269. // Effects
  54270. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  54271. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  54272. }
  54273. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  54274. set: function (callback) {
  54275. if (this._onDisposeObserver) {
  54276. this.onDisposeObservable.remove(this._onDisposeObserver);
  54277. }
  54278. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  54279. },
  54280. enumerable: true,
  54281. configurable: true
  54282. });
  54283. Object.defineProperty(SpriteManager.prototype, "texture", {
  54284. get: function () {
  54285. return this._spriteTexture;
  54286. },
  54287. set: function (value) {
  54288. this._spriteTexture = value;
  54289. },
  54290. enumerable: true,
  54291. configurable: true
  54292. });
  54293. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  54294. var arrayOffset = index * 16;
  54295. if (offsetX === 0)
  54296. offsetX = this._epsilon;
  54297. else if (offsetX === 1)
  54298. offsetX = 1 - this._epsilon;
  54299. if (offsetY === 0)
  54300. offsetY = this._epsilon;
  54301. else if (offsetY === 1)
  54302. offsetY = 1 - this._epsilon;
  54303. this._vertexData[arrayOffset] = sprite.position.x;
  54304. this._vertexData[arrayOffset + 1] = sprite.position.y;
  54305. this._vertexData[arrayOffset + 2] = sprite.position.z;
  54306. this._vertexData[arrayOffset + 3] = sprite.angle;
  54307. this._vertexData[arrayOffset + 4] = sprite.width;
  54308. this._vertexData[arrayOffset + 5] = sprite.height;
  54309. this._vertexData[arrayOffset + 6] = offsetX;
  54310. this._vertexData[arrayOffset + 7] = offsetY;
  54311. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  54312. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  54313. var offset = (sprite.cellIndex / rowSize) >> 0;
  54314. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  54315. this._vertexData[arrayOffset + 11] = offset;
  54316. // Color
  54317. this._vertexData[arrayOffset + 12] = sprite.color.r;
  54318. this._vertexData[arrayOffset + 13] = sprite.color.g;
  54319. this._vertexData[arrayOffset + 14] = sprite.color.b;
  54320. this._vertexData[arrayOffset + 15] = sprite.color.a;
  54321. };
  54322. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  54323. var count = Math.min(this._capacity, this.sprites.length);
  54324. var min = BABYLON.Vector3.Zero();
  54325. var max = BABYLON.Vector3.Zero();
  54326. var distance = Number.MAX_VALUE;
  54327. var currentSprite = null;
  54328. var cameraSpacePosition = BABYLON.Vector3.Zero();
  54329. var cameraView = camera.getViewMatrix();
  54330. for (var index = 0; index < count; index++) {
  54331. var sprite = this.sprites[index];
  54332. if (!sprite) {
  54333. continue;
  54334. }
  54335. if (predicate) {
  54336. if (!predicate(sprite)) {
  54337. continue;
  54338. }
  54339. }
  54340. else if (!sprite.isPickable) {
  54341. continue;
  54342. }
  54343. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  54344. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  54345. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  54346. if (ray.intersectsBoxMinMax(min, max)) {
  54347. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  54348. if (distance > currentDistance) {
  54349. distance = currentDistance;
  54350. currentSprite = sprite;
  54351. if (fastCheck) {
  54352. break;
  54353. }
  54354. }
  54355. }
  54356. }
  54357. if (currentSprite) {
  54358. var result = new BABYLON.PickingInfo();
  54359. result.hit = true;
  54360. result.pickedSprite = currentSprite;
  54361. result.distance = distance;
  54362. return result;
  54363. }
  54364. return null;
  54365. };
  54366. SpriteManager.prototype.render = function () {
  54367. // Check
  54368. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  54369. return;
  54370. var engine = this._scene.getEngine();
  54371. var baseSize = this._spriteTexture.getBaseSize();
  54372. // Sprites
  54373. var deltaTime = engine.getDeltaTime();
  54374. var max = Math.min(this._capacity, this.sprites.length);
  54375. var rowSize = baseSize.width / this.cellWidth;
  54376. var offset = 0;
  54377. for (var index = 0; index < max; index++) {
  54378. var sprite = this.sprites[index];
  54379. if (!sprite) {
  54380. continue;
  54381. }
  54382. sprite._animate(deltaTime);
  54383. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  54384. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  54385. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  54386. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  54387. }
  54388. this._buffer.update(this._vertexData);
  54389. // Render
  54390. var effect = this._effectBase;
  54391. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54392. effect = this._effectFog;
  54393. }
  54394. engine.enableEffect(effect);
  54395. var viewMatrix = this._scene.getViewMatrix();
  54396. effect.setTexture("diffuseSampler", this._spriteTexture);
  54397. effect.setMatrix("view", viewMatrix);
  54398. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  54399. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  54400. // Fog
  54401. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54402. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  54403. effect.setColor3("vFogColor", this._scene.fogColor);
  54404. }
  54405. // VBOs
  54406. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  54407. // Draw order
  54408. engine.setDepthFunctionToLessOrEqual();
  54409. effect.setBool("alphaTest", true);
  54410. engine.setColorWrite(false);
  54411. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  54412. engine.setColorWrite(true);
  54413. effect.setBool("alphaTest", false);
  54414. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  54415. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  54416. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  54417. };
  54418. SpriteManager.prototype.dispose = function () {
  54419. if (this._buffer) {
  54420. this._buffer.dispose();
  54421. this._buffer = null;
  54422. }
  54423. if (this._indexBuffer) {
  54424. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  54425. this._indexBuffer = null;
  54426. }
  54427. if (this._spriteTexture) {
  54428. this._spriteTexture.dispose();
  54429. this._spriteTexture = null;
  54430. }
  54431. // Remove from scene
  54432. var index = this._scene.spriteManagers.indexOf(this);
  54433. this._scene.spriteManagers.splice(index, 1);
  54434. // Callback
  54435. this.onDisposeObservable.notifyObservers(this);
  54436. this.onDisposeObservable.clear();
  54437. };
  54438. return SpriteManager;
  54439. }());
  54440. BABYLON.SpriteManager = SpriteManager;
  54441. })(BABYLON || (BABYLON = {}));
  54442. //# sourceMappingURL=babylon.spriteManager.js.map
  54443. var BABYLON;
  54444. (function (BABYLON) {
  54445. var Sprite = /** @class */ (function () {
  54446. function Sprite(name, manager) {
  54447. this.name = name;
  54448. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54449. this.width = 1.0;
  54450. this.height = 1.0;
  54451. this.angle = 0;
  54452. this.cellIndex = 0;
  54453. this.invertU = 0;
  54454. this.invertV = 0;
  54455. this.animations = new Array();
  54456. this.isPickable = false;
  54457. this._animationStarted = false;
  54458. this._loopAnimation = false;
  54459. this._fromIndex = 0;
  54460. this._toIndex = 0;
  54461. this._delay = 0;
  54462. this._direction = 1;
  54463. this._time = 0;
  54464. this._manager = manager;
  54465. this._manager.sprites.push(this);
  54466. this.position = BABYLON.Vector3.Zero();
  54467. }
  54468. Object.defineProperty(Sprite.prototype, "size", {
  54469. get: function () {
  54470. return this.width;
  54471. },
  54472. set: function (value) {
  54473. this.width = value;
  54474. this.height = value;
  54475. },
  54476. enumerable: true,
  54477. configurable: true
  54478. });
  54479. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  54480. this._fromIndex = from;
  54481. this._toIndex = to;
  54482. this._loopAnimation = loop;
  54483. this._delay = delay;
  54484. this._animationStarted = true;
  54485. this._direction = from < to ? 1 : -1;
  54486. this.cellIndex = from;
  54487. this._time = 0;
  54488. this._onAnimationEnd = onAnimationEnd;
  54489. };
  54490. Sprite.prototype.stopAnimation = function () {
  54491. this._animationStarted = false;
  54492. };
  54493. Sprite.prototype._animate = function (deltaTime) {
  54494. if (!this._animationStarted)
  54495. return;
  54496. this._time += deltaTime;
  54497. if (this._time > this._delay) {
  54498. this._time = this._time % this._delay;
  54499. this.cellIndex += this._direction;
  54500. if (this.cellIndex > this._toIndex) {
  54501. if (this._loopAnimation) {
  54502. this.cellIndex = this._fromIndex;
  54503. }
  54504. else {
  54505. this.cellIndex = this._toIndex;
  54506. this._animationStarted = false;
  54507. if (this._onAnimationEnd) {
  54508. this._onAnimationEnd();
  54509. }
  54510. if (this.disposeWhenFinishedAnimating) {
  54511. this.dispose();
  54512. }
  54513. }
  54514. }
  54515. }
  54516. };
  54517. Sprite.prototype.dispose = function () {
  54518. for (var i = 0; i < this._manager.sprites.length; i++) {
  54519. if (this._manager.sprites[i] == this) {
  54520. this._manager.sprites.splice(i, 1);
  54521. }
  54522. }
  54523. };
  54524. return Sprite;
  54525. }());
  54526. BABYLON.Sprite = Sprite;
  54527. })(BABYLON || (BABYLON = {}));
  54528. //# sourceMappingURL=babylon.sprite.js.map
  54529. var BABYLON;
  54530. (function (BABYLON) {
  54531. var IntersectionInfo = /** @class */ (function () {
  54532. function IntersectionInfo(bu, bv, distance) {
  54533. this.bu = bu;
  54534. this.bv = bv;
  54535. this.distance = distance;
  54536. this.faceId = 0;
  54537. this.subMeshId = 0;
  54538. }
  54539. return IntersectionInfo;
  54540. }());
  54541. BABYLON.IntersectionInfo = IntersectionInfo;
  54542. var PickingInfo = /** @class */ (function () {
  54543. function PickingInfo() {
  54544. this.hit = false;
  54545. this.distance = 0;
  54546. this.pickedPoint = null;
  54547. this.pickedMesh = null;
  54548. this.bu = 0;
  54549. this.bv = 0;
  54550. this.faceId = -1;
  54551. this.subMeshId = 0;
  54552. this.pickedSprite = null;
  54553. }
  54554. // Methods
  54555. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  54556. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  54557. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  54558. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  54559. return null;
  54560. }
  54561. var indices = this.pickedMesh.getIndices();
  54562. if (!indices) {
  54563. return null;
  54564. }
  54565. var result;
  54566. if (useVerticesNormals) {
  54567. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54568. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  54569. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  54570. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  54571. normal0 = normal0.scale(this.bu);
  54572. normal1 = normal1.scale(this.bv);
  54573. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  54574. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  54575. }
  54576. else {
  54577. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54578. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  54579. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  54580. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  54581. var p1p2 = vertex1.subtract(vertex2);
  54582. var p3p2 = vertex3.subtract(vertex2);
  54583. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  54584. }
  54585. if (useWorldCoordinates) {
  54586. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  54587. }
  54588. return BABYLON.Vector3.Normalize(result);
  54589. };
  54590. PickingInfo.prototype.getTextureCoordinates = function () {
  54591. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  54592. return null;
  54593. }
  54594. var indices = this.pickedMesh.getIndices();
  54595. if (!indices) {
  54596. return null;
  54597. }
  54598. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54599. if (!uvs) {
  54600. return null;
  54601. }
  54602. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  54603. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  54604. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  54605. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  54606. uv1 = uv1.scale(this.bu);
  54607. uv2 = uv2.scale(this.bv);
  54608. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  54609. };
  54610. return PickingInfo;
  54611. }());
  54612. BABYLON.PickingInfo = PickingInfo;
  54613. })(BABYLON || (BABYLON = {}));
  54614. //# sourceMappingURL=babylon.pickingInfo.js.map
  54615. var BABYLON;
  54616. (function (BABYLON) {
  54617. var Ray = /** @class */ (function () {
  54618. function Ray(origin, direction, length) {
  54619. if (length === void 0) { length = Number.MAX_VALUE; }
  54620. this.origin = origin;
  54621. this.direction = direction;
  54622. this.length = length;
  54623. }
  54624. // Methods
  54625. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  54626. var d = 0.0;
  54627. var maxValue = Number.MAX_VALUE;
  54628. var inv;
  54629. var min;
  54630. var max;
  54631. var temp;
  54632. if (Math.abs(this.direction.x) < 0.0000001) {
  54633. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  54634. return false;
  54635. }
  54636. }
  54637. else {
  54638. inv = 1.0 / this.direction.x;
  54639. min = (minimum.x - this.origin.x) * inv;
  54640. max = (maximum.x - this.origin.x) * inv;
  54641. if (max === -Infinity) {
  54642. max = Infinity;
  54643. }
  54644. if (min > max) {
  54645. temp = min;
  54646. min = max;
  54647. max = temp;
  54648. }
  54649. d = Math.max(min, d);
  54650. maxValue = Math.min(max, maxValue);
  54651. if (d > maxValue) {
  54652. return false;
  54653. }
  54654. }
  54655. if (Math.abs(this.direction.y) < 0.0000001) {
  54656. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  54657. return false;
  54658. }
  54659. }
  54660. else {
  54661. inv = 1.0 / this.direction.y;
  54662. min = (minimum.y - this.origin.y) * inv;
  54663. max = (maximum.y - this.origin.y) * inv;
  54664. if (max === -Infinity) {
  54665. max = Infinity;
  54666. }
  54667. if (min > max) {
  54668. temp = min;
  54669. min = max;
  54670. max = temp;
  54671. }
  54672. d = Math.max(min, d);
  54673. maxValue = Math.min(max, maxValue);
  54674. if (d > maxValue) {
  54675. return false;
  54676. }
  54677. }
  54678. if (Math.abs(this.direction.z) < 0.0000001) {
  54679. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  54680. return false;
  54681. }
  54682. }
  54683. else {
  54684. inv = 1.0 / this.direction.z;
  54685. min = (minimum.z - this.origin.z) * inv;
  54686. max = (maximum.z - this.origin.z) * inv;
  54687. if (max === -Infinity) {
  54688. max = Infinity;
  54689. }
  54690. if (min > max) {
  54691. temp = min;
  54692. min = max;
  54693. max = temp;
  54694. }
  54695. d = Math.max(min, d);
  54696. maxValue = Math.min(max, maxValue);
  54697. if (d > maxValue) {
  54698. return false;
  54699. }
  54700. }
  54701. return true;
  54702. };
  54703. Ray.prototype.intersectsBox = function (box) {
  54704. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  54705. };
  54706. Ray.prototype.intersectsSphere = function (sphere) {
  54707. var x = sphere.center.x - this.origin.x;
  54708. var y = sphere.center.y - this.origin.y;
  54709. var z = sphere.center.z - this.origin.z;
  54710. var pyth = (x * x) + (y * y) + (z * z);
  54711. var rr = sphere.radius * sphere.radius;
  54712. if (pyth <= rr) {
  54713. return true;
  54714. }
  54715. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  54716. if (dot < 0.0) {
  54717. return false;
  54718. }
  54719. var temp = pyth - (dot * dot);
  54720. return temp <= rr;
  54721. };
  54722. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  54723. if (!this._edge1) {
  54724. this._edge1 = BABYLON.Vector3.Zero();
  54725. this._edge2 = BABYLON.Vector3.Zero();
  54726. this._pvec = BABYLON.Vector3.Zero();
  54727. this._tvec = BABYLON.Vector3.Zero();
  54728. this._qvec = BABYLON.Vector3.Zero();
  54729. }
  54730. vertex1.subtractToRef(vertex0, this._edge1);
  54731. vertex2.subtractToRef(vertex0, this._edge2);
  54732. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  54733. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  54734. if (det === 0) {
  54735. return null;
  54736. }
  54737. var invdet = 1 / det;
  54738. this.origin.subtractToRef(vertex0, this._tvec);
  54739. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  54740. if (bu < 0 || bu > 1.0) {
  54741. return null;
  54742. }
  54743. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  54744. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  54745. if (bv < 0 || bu + bv > 1.0) {
  54746. return null;
  54747. }
  54748. //check if the distance is longer than the predefined length.
  54749. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  54750. if (distance > this.length) {
  54751. return null;
  54752. }
  54753. return new BABYLON.IntersectionInfo(bu, bv, distance);
  54754. };
  54755. Ray.prototype.intersectsPlane = function (plane) {
  54756. var distance;
  54757. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  54758. if (Math.abs(result1) < 9.99999997475243E-07) {
  54759. return null;
  54760. }
  54761. else {
  54762. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  54763. distance = (-plane.d - result2) / result1;
  54764. if (distance < 0.0) {
  54765. if (distance < -9.99999997475243E-07) {
  54766. return null;
  54767. }
  54768. else {
  54769. return 0;
  54770. }
  54771. }
  54772. return distance;
  54773. }
  54774. };
  54775. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  54776. var tm = BABYLON.Tmp.Matrix[0];
  54777. mesh.getWorldMatrix().invertToRef(tm);
  54778. if (this._tmpRay) {
  54779. Ray.TransformToRef(this, tm, this._tmpRay);
  54780. }
  54781. else {
  54782. this._tmpRay = Ray.Transform(this, tm);
  54783. }
  54784. return mesh.intersects(this._tmpRay, fastCheck);
  54785. };
  54786. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  54787. if (results) {
  54788. results.length = 0;
  54789. }
  54790. else {
  54791. results = [];
  54792. }
  54793. for (var i = 0; i < meshes.length; i++) {
  54794. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  54795. if (pickInfo.hit) {
  54796. results.push(pickInfo);
  54797. }
  54798. }
  54799. results.sort(this._comparePickingInfo);
  54800. return results;
  54801. };
  54802. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  54803. if (pickingInfoA.distance < pickingInfoB.distance) {
  54804. return -1;
  54805. }
  54806. else if (pickingInfoA.distance > pickingInfoB.distance) {
  54807. return 1;
  54808. }
  54809. else {
  54810. return 0;
  54811. }
  54812. };
  54813. /**
  54814. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  54815. * @param sega the first point of the segment to test the intersection against
  54816. * @param segb the second point of the segment to test the intersection against
  54817. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  54818. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  54819. */
  54820. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  54821. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  54822. var u = segb.subtract(sega);
  54823. var v = rsegb.subtract(this.origin);
  54824. var w = sega.subtract(this.origin);
  54825. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  54826. var b = BABYLON.Vector3.Dot(u, v);
  54827. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  54828. var d = BABYLON.Vector3.Dot(u, w);
  54829. var e = BABYLON.Vector3.Dot(v, w);
  54830. var D = a * c - b * b; // always >= 0
  54831. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  54832. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  54833. // compute the line parameters of the two closest points
  54834. if (D < Ray.smallnum) { // the lines are almost parallel
  54835. sN = 0.0; // force using point P0 on segment S1
  54836. sD = 1.0; // to prevent possible division by 0.0 later
  54837. tN = e;
  54838. tD = c;
  54839. }
  54840. else { // get the closest points on the infinite lines
  54841. sN = (b * e - c * d);
  54842. tN = (a * e - b * d);
  54843. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  54844. sN = 0.0;
  54845. tN = e;
  54846. tD = c;
  54847. }
  54848. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  54849. sN = sD;
  54850. tN = e + b;
  54851. tD = c;
  54852. }
  54853. }
  54854. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  54855. tN = 0.0;
  54856. // recompute sc for this edge
  54857. if (-d < 0.0) {
  54858. sN = 0.0;
  54859. }
  54860. else if (-d > a)
  54861. sN = sD;
  54862. else {
  54863. sN = -d;
  54864. sD = a;
  54865. }
  54866. }
  54867. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  54868. tN = tD;
  54869. // recompute sc for this edge
  54870. if ((-d + b) < 0.0) {
  54871. sN = 0;
  54872. }
  54873. else if ((-d + b) > a) {
  54874. sN = sD;
  54875. }
  54876. else {
  54877. sN = (-d + b);
  54878. sD = a;
  54879. }
  54880. }
  54881. // finally do the division to get sc and tc
  54882. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  54883. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  54884. // get the difference of the two closest points
  54885. var qtc = v.multiplyByFloats(tc, tc, tc);
  54886. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  54887. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  54888. if (isIntersected) {
  54889. return qtc.length();
  54890. }
  54891. return -1;
  54892. };
  54893. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54894. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  54895. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  54896. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  54897. this.direction.normalize();
  54898. return this;
  54899. };
  54900. // Statics
  54901. Ray.Zero = function () {
  54902. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  54903. };
  54904. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54905. var result = Ray.Zero();
  54906. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  54907. };
  54908. /**
  54909. * 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
  54910. * transformed to the given world matrix.
  54911. * @param origin The origin point
  54912. * @param end The end point
  54913. * @param world a matrix to transform the ray to. Default is the identity matrix.
  54914. */
  54915. Ray.CreateNewFromTo = function (origin, end, world) {
  54916. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  54917. var direction = end.subtract(origin);
  54918. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  54919. direction.normalize();
  54920. return Ray.Transform(new Ray(origin, direction, length), world);
  54921. };
  54922. Ray.Transform = function (ray, matrix) {
  54923. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  54924. Ray.TransformToRef(ray, matrix, result);
  54925. return result;
  54926. };
  54927. Ray.TransformToRef = function (ray, matrix, result) {
  54928. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  54929. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  54930. result.length = ray.length;
  54931. var dir = result.direction;
  54932. var len = dir.length();
  54933. if (!(len === 0 || len === 1)) {
  54934. var num = 1.0 / len;
  54935. dir.x *= num;
  54936. dir.y *= num;
  54937. dir.z *= num;
  54938. result.length *= len;
  54939. }
  54940. };
  54941. Ray.smallnum = 0.00000001;
  54942. Ray.rayl = 10e8;
  54943. return Ray;
  54944. }());
  54945. BABYLON.Ray = Ray;
  54946. })(BABYLON || (BABYLON = {}));
  54947. //# sourceMappingURL=babylon.ray.js.map
  54948. var BABYLON;
  54949. (function (BABYLON) {
  54950. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  54951. if (boxMin.x > sphereCenter.x + sphereRadius)
  54952. return false;
  54953. if (sphereCenter.x - sphereRadius > boxMax.x)
  54954. return false;
  54955. if (boxMin.y > sphereCenter.y + sphereRadius)
  54956. return false;
  54957. if (sphereCenter.y - sphereRadius > boxMax.y)
  54958. return false;
  54959. if (boxMin.z > sphereCenter.z + sphereRadius)
  54960. return false;
  54961. if (sphereCenter.z - sphereRadius > boxMax.z)
  54962. return false;
  54963. return true;
  54964. };
  54965. var getLowestRoot = (function () {
  54966. var result = { root: 0, found: false };
  54967. return function (a, b, c, maxR) {
  54968. result.root = 0;
  54969. result.found = false;
  54970. var determinant = b * b - 4.0 * a * c;
  54971. if (determinant < 0)
  54972. return result;
  54973. var sqrtD = Math.sqrt(determinant);
  54974. var r1 = (-b - sqrtD) / (2.0 * a);
  54975. var r2 = (-b + sqrtD) / (2.0 * a);
  54976. if (r1 > r2) {
  54977. var temp = r2;
  54978. r2 = r1;
  54979. r1 = temp;
  54980. }
  54981. if (r1 > 0 && r1 < maxR) {
  54982. result.root = r1;
  54983. result.found = true;
  54984. return result;
  54985. }
  54986. if (r2 > 0 && r2 < maxR) {
  54987. result.root = r2;
  54988. result.found = true;
  54989. return result;
  54990. }
  54991. return result;
  54992. };
  54993. })();
  54994. var Collider = /** @class */ (function () {
  54995. function Collider() {
  54996. this._collisionPoint = BABYLON.Vector3.Zero();
  54997. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  54998. this._tempVector = BABYLON.Vector3.Zero();
  54999. this._tempVector2 = BABYLON.Vector3.Zero();
  55000. this._tempVector3 = BABYLON.Vector3.Zero();
  55001. this._tempVector4 = BABYLON.Vector3.Zero();
  55002. this._edge = BABYLON.Vector3.Zero();
  55003. this._baseToVertex = BABYLON.Vector3.Zero();
  55004. this._destinationPoint = BABYLON.Vector3.Zero();
  55005. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  55006. this._displacementVector = BABYLON.Vector3.Zero();
  55007. this._radius = BABYLON.Vector3.One();
  55008. this._retry = 0;
  55009. this._basePointWorld = BABYLON.Vector3.Zero();
  55010. this._velocityWorld = BABYLON.Vector3.Zero();
  55011. this._normalizedVelocity = BABYLON.Vector3.Zero();
  55012. this._collisionMask = -1;
  55013. }
  55014. Object.defineProperty(Collider.prototype, "collisionMask", {
  55015. get: function () {
  55016. return this._collisionMask;
  55017. },
  55018. set: function (mask) {
  55019. this._collisionMask = !isNaN(mask) ? mask : -1;
  55020. },
  55021. enumerable: true,
  55022. configurable: true
  55023. });
  55024. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  55025. /**
  55026. * Gets the plane normal used to compute the sliding response (in local space)
  55027. */
  55028. get: function () {
  55029. return this._slidePlaneNormal;
  55030. },
  55031. enumerable: true,
  55032. configurable: true
  55033. });
  55034. // Methods
  55035. Collider.prototype._initialize = function (source, dir, e) {
  55036. this._velocity = dir;
  55037. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  55038. this._basePoint = source;
  55039. source.multiplyToRef(this._radius, this._basePointWorld);
  55040. dir.multiplyToRef(this._radius, this._velocityWorld);
  55041. this._velocityWorldLength = this._velocityWorld.length();
  55042. this._epsilon = e;
  55043. this.collisionFound = false;
  55044. };
  55045. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  55046. pa.subtractToRef(point, this._tempVector);
  55047. pb.subtractToRef(point, this._tempVector2);
  55048. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  55049. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55050. if (d < 0)
  55051. return false;
  55052. pc.subtractToRef(point, this._tempVector3);
  55053. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  55054. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55055. if (d < 0)
  55056. return false;
  55057. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  55058. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55059. return d >= 0;
  55060. };
  55061. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  55062. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  55063. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  55064. if (distance > this._velocityWorldLength + max + sphereRadius) {
  55065. return false;
  55066. }
  55067. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  55068. return false;
  55069. return true;
  55070. };
  55071. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  55072. var t0;
  55073. var embeddedInPlane = false;
  55074. //defensive programming, actually not needed.
  55075. if (!trianglePlaneArray) {
  55076. trianglePlaneArray = [];
  55077. }
  55078. if (!trianglePlaneArray[faceIndex]) {
  55079. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  55080. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  55081. }
  55082. var trianglePlane = trianglePlaneArray[faceIndex];
  55083. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  55084. return;
  55085. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  55086. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  55087. if (normalDotVelocity == 0) {
  55088. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  55089. return;
  55090. embeddedInPlane = true;
  55091. t0 = 0;
  55092. }
  55093. else {
  55094. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  55095. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  55096. if (t0 > t1) {
  55097. var temp = t1;
  55098. t1 = t0;
  55099. t0 = temp;
  55100. }
  55101. if (t0 > 1.0 || t1 < 0.0)
  55102. return;
  55103. if (t0 < 0)
  55104. t0 = 0;
  55105. if (t0 > 1.0)
  55106. t0 = 1.0;
  55107. }
  55108. this._collisionPoint.copyFromFloats(0, 0, 0);
  55109. var found = false;
  55110. var t = 1.0;
  55111. if (!embeddedInPlane) {
  55112. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  55113. this._velocity.scaleToRef(t0, this._tempVector);
  55114. this._planeIntersectionPoint.addInPlace(this._tempVector);
  55115. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  55116. found = true;
  55117. t = t0;
  55118. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  55119. }
  55120. }
  55121. if (!found) {
  55122. var velocitySquaredLength = this._velocity.lengthSquared();
  55123. var a = velocitySquaredLength;
  55124. this._basePoint.subtractToRef(p1, this._tempVector);
  55125. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55126. var c = this._tempVector.lengthSquared() - 1.0;
  55127. var lowestRoot = getLowestRoot(a, b, c, t);
  55128. if (lowestRoot.found) {
  55129. t = lowestRoot.root;
  55130. found = true;
  55131. this._collisionPoint.copyFrom(p1);
  55132. }
  55133. this._basePoint.subtractToRef(p2, this._tempVector);
  55134. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55135. c = this._tempVector.lengthSquared() - 1.0;
  55136. lowestRoot = getLowestRoot(a, b, c, t);
  55137. if (lowestRoot.found) {
  55138. t = lowestRoot.root;
  55139. found = true;
  55140. this._collisionPoint.copyFrom(p2);
  55141. }
  55142. this._basePoint.subtractToRef(p3, this._tempVector);
  55143. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55144. c = this._tempVector.lengthSquared() - 1.0;
  55145. lowestRoot = getLowestRoot(a, b, c, t);
  55146. if (lowestRoot.found) {
  55147. t = lowestRoot.root;
  55148. found = true;
  55149. this._collisionPoint.copyFrom(p3);
  55150. }
  55151. p2.subtractToRef(p1, this._edge);
  55152. p1.subtractToRef(this._basePoint, this._baseToVertex);
  55153. var edgeSquaredLength = this._edge.lengthSquared();
  55154. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55155. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55156. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55157. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55158. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55159. lowestRoot = getLowestRoot(a, b, c, t);
  55160. if (lowestRoot.found) {
  55161. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55162. if (f >= 0.0 && f <= 1.0) {
  55163. t = lowestRoot.root;
  55164. found = true;
  55165. this._edge.scaleInPlace(f);
  55166. p1.addToRef(this._edge, this._collisionPoint);
  55167. }
  55168. }
  55169. p3.subtractToRef(p2, this._edge);
  55170. p2.subtractToRef(this._basePoint, this._baseToVertex);
  55171. edgeSquaredLength = this._edge.lengthSquared();
  55172. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55173. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55174. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55175. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55176. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55177. lowestRoot = getLowestRoot(a, b, c, t);
  55178. if (lowestRoot.found) {
  55179. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55180. if (f >= 0.0 && f <= 1.0) {
  55181. t = lowestRoot.root;
  55182. found = true;
  55183. this._edge.scaleInPlace(f);
  55184. p2.addToRef(this._edge, this._collisionPoint);
  55185. }
  55186. }
  55187. p1.subtractToRef(p3, this._edge);
  55188. p3.subtractToRef(this._basePoint, this._baseToVertex);
  55189. edgeSquaredLength = this._edge.lengthSquared();
  55190. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55191. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55192. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55193. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55194. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55195. lowestRoot = getLowestRoot(a, b, c, t);
  55196. if (lowestRoot.found) {
  55197. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55198. if (f >= 0.0 && f <= 1.0) {
  55199. t = lowestRoot.root;
  55200. found = true;
  55201. this._edge.scaleInPlace(f);
  55202. p3.addToRef(this._edge, this._collisionPoint);
  55203. }
  55204. }
  55205. }
  55206. if (found) {
  55207. var distToCollision = t * this._velocity.length();
  55208. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  55209. if (!this.intersectionPoint) {
  55210. this.intersectionPoint = this._collisionPoint.clone();
  55211. }
  55212. else {
  55213. this.intersectionPoint.copyFrom(this._collisionPoint);
  55214. }
  55215. this._nearestDistance = distToCollision;
  55216. this.collisionFound = true;
  55217. }
  55218. }
  55219. };
  55220. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  55221. for (var i = indexStart; i < indexEnd; i += 3) {
  55222. var p1 = pts[indices[i] - decal];
  55223. var p2 = pts[indices[i + 1] - decal];
  55224. var p3 = pts[indices[i + 2] - decal];
  55225. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  55226. }
  55227. };
  55228. Collider.prototype._getResponse = function (pos, vel) {
  55229. pos.addToRef(vel, this._destinationPoint);
  55230. vel.scaleInPlace((this._nearestDistance / vel.length()));
  55231. this._basePoint.addToRef(vel, pos);
  55232. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  55233. this._slidePlaneNormal.normalize();
  55234. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  55235. pos.addInPlace(this._displacementVector);
  55236. this.intersectionPoint.addInPlace(this._displacementVector);
  55237. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  55238. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  55239. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  55240. };
  55241. return Collider;
  55242. }());
  55243. BABYLON.Collider = Collider;
  55244. })(BABYLON || (BABYLON = {}));
  55245. //# sourceMappingURL=babylon.collider.js.map
  55246. var BABYLON;
  55247. (function (BABYLON) {
  55248. //WebWorker code will be inserted to this variable.
  55249. BABYLON.CollisionWorker = "";
  55250. /** Defines supported task for worker process */
  55251. var WorkerTaskType;
  55252. (function (WorkerTaskType) {
  55253. /** Initialization */
  55254. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  55255. /** Update of geometry */
  55256. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  55257. /** Evaluate collision */
  55258. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  55259. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  55260. /** Defines kind of replies returned by worker */
  55261. var WorkerReplyType;
  55262. (function (WorkerReplyType) {
  55263. /** Success */
  55264. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  55265. /** Unkown error */
  55266. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  55267. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  55268. var CollisionCoordinatorWorker = /** @class */ (function () {
  55269. function CollisionCoordinatorWorker() {
  55270. var _this = this;
  55271. this._scaledPosition = BABYLON.Vector3.Zero();
  55272. this._scaledVelocity = BABYLON.Vector3.Zero();
  55273. this.onMeshUpdated = function (transformNode) {
  55274. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  55275. };
  55276. this.onGeometryUpdated = function (geometry) {
  55277. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  55278. };
  55279. this._afterRender = function () {
  55280. if (!_this._init)
  55281. return;
  55282. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  55283. return;
  55284. }
  55285. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  55286. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  55287. if (_this._runningUpdated > 4) {
  55288. return;
  55289. }
  55290. ++_this._runningUpdated;
  55291. var payload = {
  55292. updatedMeshes: _this._addUpdateMeshesList,
  55293. updatedGeometries: _this._addUpdateGeometriesList,
  55294. removedGeometries: _this._toRemoveGeometryArray,
  55295. removedMeshes: _this._toRemoveMeshesArray
  55296. };
  55297. var message = {
  55298. payload: payload,
  55299. taskType: WorkerTaskType.UPDATE
  55300. };
  55301. var serializable = [];
  55302. for (var id in payload.updatedGeometries) {
  55303. if (payload.updatedGeometries.hasOwnProperty(id)) {
  55304. //prepare transferables
  55305. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  55306. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  55307. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  55308. }
  55309. }
  55310. _this._worker.postMessage(message, serializable);
  55311. _this._addUpdateMeshesList = {};
  55312. _this._addUpdateGeometriesList = {};
  55313. _this._toRemoveGeometryArray = [];
  55314. _this._toRemoveMeshesArray = [];
  55315. };
  55316. this._onMessageFromWorker = function (e) {
  55317. var returnData = e.data;
  55318. if (returnData.error != WorkerReplyType.SUCCESS) {
  55319. //TODO what errors can be returned from the worker?
  55320. BABYLON.Tools.Warn("error returned from worker!");
  55321. return;
  55322. }
  55323. switch (returnData.taskType) {
  55324. case WorkerTaskType.INIT:
  55325. _this._init = true;
  55326. //Update the worked with ALL of the scene's current state
  55327. _this._scene.meshes.forEach(function (mesh) {
  55328. _this.onMeshAdded(mesh);
  55329. });
  55330. _this._scene.getGeometries().forEach(function (geometry) {
  55331. _this.onGeometryAdded(geometry);
  55332. });
  55333. break;
  55334. case WorkerTaskType.UPDATE:
  55335. _this._runningUpdated--;
  55336. break;
  55337. case WorkerTaskType.COLLIDE:
  55338. var returnPayload = returnData.payload;
  55339. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  55340. return;
  55341. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  55342. if (callback) {
  55343. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  55344. if (mesh) {
  55345. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  55346. }
  55347. }
  55348. //cleanup
  55349. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  55350. break;
  55351. }
  55352. };
  55353. this._collisionsCallbackArray = [];
  55354. this._init = false;
  55355. this._runningUpdated = 0;
  55356. this._addUpdateMeshesList = {};
  55357. this._addUpdateGeometriesList = {};
  55358. this._toRemoveGeometryArray = [];
  55359. this._toRemoveMeshesArray = [];
  55360. }
  55361. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55362. if (!this._init)
  55363. return;
  55364. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  55365. return;
  55366. position.divideToRef(collider._radius, this._scaledPosition);
  55367. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55368. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  55369. var payload = {
  55370. collider: {
  55371. position: this._scaledPosition.asArray(),
  55372. velocity: this._scaledVelocity.asArray(),
  55373. radius: collider._radius.asArray()
  55374. },
  55375. collisionId: collisionIndex,
  55376. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  55377. maximumRetry: maximumRetry
  55378. };
  55379. var message = {
  55380. payload: payload,
  55381. taskType: WorkerTaskType.COLLIDE
  55382. };
  55383. this._worker.postMessage(message);
  55384. };
  55385. CollisionCoordinatorWorker.prototype.init = function (scene) {
  55386. this._scene = scene;
  55387. this._scene.registerAfterRender(this._afterRender);
  55388. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  55389. this._worker = new Worker(workerUrl);
  55390. this._worker.onmessage = this._onMessageFromWorker;
  55391. var message = {
  55392. payload: {},
  55393. taskType: WorkerTaskType.INIT
  55394. };
  55395. this._worker.postMessage(message);
  55396. };
  55397. CollisionCoordinatorWorker.prototype.destroy = function () {
  55398. this._scene.unregisterAfterRender(this._afterRender);
  55399. this._worker.terminate();
  55400. };
  55401. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  55402. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  55403. this.onMeshUpdated(mesh);
  55404. };
  55405. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  55406. this._toRemoveMeshesArray.push(mesh.uniqueId);
  55407. };
  55408. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  55409. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  55410. geometry.onGeometryUpdated = this.onGeometryUpdated;
  55411. this.onGeometryUpdated(geometry);
  55412. };
  55413. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  55414. this._toRemoveGeometryArray.push(geometry.id);
  55415. };
  55416. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  55417. var submeshes = [];
  55418. if (mesh.subMeshes) {
  55419. submeshes = mesh.subMeshes.map(function (sm, idx) {
  55420. var boundingInfo = sm.getBoundingInfo();
  55421. return {
  55422. position: idx,
  55423. verticesStart: sm.verticesStart,
  55424. verticesCount: sm.verticesCount,
  55425. indexStart: sm.indexStart,
  55426. indexCount: sm.indexCount,
  55427. hasMaterial: !!sm.getMaterial(),
  55428. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55429. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55430. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55431. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  55432. };
  55433. });
  55434. }
  55435. var geometryId = null;
  55436. if (mesh instanceof BABYLON.Mesh) {
  55437. var geometry = mesh.geometry;
  55438. geometryId = geometry ? geometry.id : null;
  55439. }
  55440. else if (mesh instanceof BABYLON.InstancedMesh) {
  55441. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  55442. geometryId = geometry ? geometry.id : null;
  55443. }
  55444. var boundingInfo = mesh.getBoundingInfo();
  55445. return {
  55446. uniqueId: mesh.uniqueId,
  55447. id: mesh.id,
  55448. name: mesh.name,
  55449. geometryId: geometryId,
  55450. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55451. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55452. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55453. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  55454. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  55455. subMeshes: submeshes,
  55456. checkCollisions: mesh.checkCollisions
  55457. };
  55458. };
  55459. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  55460. return {
  55461. id: geometry.id,
  55462. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  55463. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  55464. indices: new Uint32Array(geometry.getIndices() || []),
  55465. };
  55466. };
  55467. return CollisionCoordinatorWorker;
  55468. }());
  55469. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  55470. var CollisionCoordinatorLegacy = /** @class */ (function () {
  55471. function CollisionCoordinatorLegacy() {
  55472. this._scaledPosition = BABYLON.Vector3.Zero();
  55473. this._scaledVelocity = BABYLON.Vector3.Zero();
  55474. this._finalPosition = BABYLON.Vector3.Zero();
  55475. }
  55476. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55477. position.divideToRef(collider._radius, this._scaledPosition);
  55478. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55479. collider.collidedMesh = null;
  55480. collider._retry = 0;
  55481. collider._initialVelocity = this._scaledVelocity;
  55482. collider._initialPosition = this._scaledPosition;
  55483. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  55484. this._finalPosition.multiplyInPlace(collider._radius);
  55485. //run the callback
  55486. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  55487. };
  55488. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  55489. this._scene = scene;
  55490. };
  55491. CollisionCoordinatorLegacy.prototype.destroy = function () {
  55492. //Legacy need no destruction method.
  55493. };
  55494. //No update in legacy mode
  55495. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  55496. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  55497. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  55498. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  55499. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  55500. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  55501. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  55502. if (excludedMesh === void 0) { excludedMesh = null; }
  55503. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  55504. if (collider._retry >= maximumRetry) {
  55505. finalPosition.copyFrom(position);
  55506. return;
  55507. }
  55508. // Check if this is a mesh else camera or -1
  55509. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  55510. collider._initialize(position, velocity, closeDistance);
  55511. // Check all meshes
  55512. for (var index = 0; index < this._scene.meshes.length; index++) {
  55513. var mesh = this._scene.meshes[index];
  55514. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  55515. mesh._checkCollision(collider);
  55516. }
  55517. }
  55518. if (!collider.collisionFound) {
  55519. position.addToRef(velocity, finalPosition);
  55520. return;
  55521. }
  55522. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  55523. collider._getResponse(position, velocity);
  55524. }
  55525. if (velocity.length() <= closeDistance) {
  55526. finalPosition.copyFrom(position);
  55527. return;
  55528. }
  55529. collider._retry++;
  55530. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  55531. };
  55532. return CollisionCoordinatorLegacy;
  55533. }());
  55534. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  55535. })(BABYLON || (BABYLON = {}));
  55536. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  55537. var BABYLON;
  55538. (function (BABYLON) {
  55539. /**
  55540. * A particle represents one of the element emitted by a particle system.
  55541. * This is mainly define by its coordinates, direction, velocity and age.
  55542. */
  55543. var Particle = /** @class */ (function () {
  55544. /**
  55545. * Creates a new instance Particle
  55546. * @param particleSystem the particle system the particle belongs to
  55547. */
  55548. function Particle(
  55549. /**
  55550. * particleSystem the particle system the particle belongs to.
  55551. */
  55552. particleSystem) {
  55553. this.particleSystem = particleSystem;
  55554. /**
  55555. * The world position of the particle in the scene.
  55556. */
  55557. this.position = BABYLON.Vector3.Zero();
  55558. /**
  55559. * The world direction of the particle in the scene.
  55560. */
  55561. this.direction = BABYLON.Vector3.Zero();
  55562. /**
  55563. * The color of the particle.
  55564. */
  55565. this.color = new BABYLON.Color4(0, 0, 0, 0);
  55566. /**
  55567. * The color change of the particle per step.
  55568. */
  55569. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  55570. /**
  55571. * Defines how long will the life of the particle be.
  55572. */
  55573. this.lifeTime = 1.0;
  55574. /**
  55575. * The current age of the particle.
  55576. */
  55577. this.age = 0;
  55578. /**
  55579. * The current size of the particle.
  55580. */
  55581. this.size = 0;
  55582. /**
  55583. * The current angle of the particle.
  55584. */
  55585. this.angle = 0;
  55586. /**
  55587. * Defines how fast is the angle changing.
  55588. */
  55589. this.angularSpeed = 0;
  55590. /**
  55591. * Defines the cell index used by the particle to be rendered from a sprite.
  55592. */
  55593. this.cellIndex = 0;
  55594. this._currentFrameCounter = 0;
  55595. if (!this.particleSystem.isAnimationSheetEnabled) {
  55596. return;
  55597. }
  55598. this.updateCellInfoFromSystem();
  55599. }
  55600. Particle.prototype.updateCellInfoFromSystem = function () {
  55601. this.cellIndex = this.particleSystem.startSpriteCellID;
  55602. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  55603. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  55604. }
  55605. else {
  55606. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  55607. }
  55608. };
  55609. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  55610. // (ageOffset / scaledUpdateSpeed) / available cells
  55611. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  55612. this._currentFrameCounter += scaledUpdateSpeed;
  55613. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  55614. this._currentFrameCounter = 0;
  55615. this.cellIndex++;
  55616. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  55617. this.cellIndex = this.particleSystem.endSpriteCellID;
  55618. }
  55619. }
  55620. };
  55621. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  55622. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  55623. this.cellIndex++;
  55624. this._currentFrameCounter = 0;
  55625. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  55626. if (this.particleSystem.spriteCellLoop) {
  55627. this.cellIndex = this.particleSystem.startSpriteCellID;
  55628. }
  55629. else {
  55630. this.cellIndex = this.particleSystem.endSpriteCellID;
  55631. }
  55632. }
  55633. }
  55634. else {
  55635. this._currentFrameCounter++;
  55636. }
  55637. };
  55638. /**
  55639. * Copy the properties of particle to another one.
  55640. * @param other the particle to copy the information to.
  55641. */
  55642. Particle.prototype.copyTo = function (other) {
  55643. other.position.copyFrom(this.position);
  55644. other.direction.copyFrom(this.direction);
  55645. other.color.copyFrom(this.color);
  55646. other.colorStep.copyFrom(this.colorStep);
  55647. other.lifeTime = this.lifeTime;
  55648. other.age = this.age;
  55649. other.size = this.size;
  55650. other.angle = this.angle;
  55651. other.angularSpeed = this.angularSpeed;
  55652. other.particleSystem = this.particleSystem;
  55653. other.cellIndex = this.cellIndex;
  55654. };
  55655. return Particle;
  55656. }());
  55657. BABYLON.Particle = Particle;
  55658. })(BABYLON || (BABYLON = {}));
  55659. //# sourceMappingURL=babylon.particle.js.map
  55660. var BABYLON;
  55661. (function (BABYLON) {
  55662. /**
  55663. * This represents a particle system in Babylon.
  55664. * 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.
  55665. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  55666. * @example https://doc.babylonjs.com/babylon101/particles
  55667. */
  55668. var ParticleSystem = /** @class */ (function () {
  55669. /**
  55670. * Instantiates a particle system.
  55671. * 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.
  55672. * @param name The name of the particle system
  55673. * @param capacity The max number of particles alive at the same time
  55674. * @param scene The scene the particle system belongs to
  55675. * @param customEffect a custom effect used to change the way particles are rendered by default
  55676. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  55677. * @param epsilon Offset used to render the particles
  55678. */
  55679. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  55680. if (customEffect === void 0) { customEffect = null; }
  55681. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  55682. if (epsilon === void 0) { epsilon = 0.01; }
  55683. var _this = this;
  55684. /**
  55685. * List of animations used by the particle system.
  55686. */
  55687. this.animations = [];
  55688. /**
  55689. * The rendering group used by the Particle system to chose when to render.
  55690. */
  55691. this.renderingGroupId = 0;
  55692. /**
  55693. * The emitter represents the Mesh or position we are attaching the particle system to.
  55694. */
  55695. this.emitter = null;
  55696. /**
  55697. * The maximum number of particles to emit per frame
  55698. */
  55699. this.emitRate = 10;
  55700. /**
  55701. * If you want to launch only a few particles at once, that can be done, as well.
  55702. */
  55703. this.manualEmitCount = -1;
  55704. /**
  55705. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  55706. */
  55707. this.updateSpeed = 0.01;
  55708. /**
  55709. * The amount of time the particle system is running (depends of the overall update speed).
  55710. */
  55711. this.targetStopDuration = 0;
  55712. /**
  55713. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  55714. */
  55715. this.disposeOnStop = false;
  55716. /**
  55717. * Minimum power of emitting particles.
  55718. */
  55719. this.minEmitPower = 1;
  55720. /**
  55721. * Maximum power of emitting particles.
  55722. */
  55723. this.maxEmitPower = 1;
  55724. /**
  55725. * Minimum life time of emitting particles.
  55726. */
  55727. this.minLifeTime = 1;
  55728. /**
  55729. * Maximum life time of emitting particles.
  55730. */
  55731. this.maxLifeTime = 1;
  55732. /**
  55733. * Minimum Size of emitting particles.
  55734. */
  55735. this.minSize = 1;
  55736. /**
  55737. * Maximum Size of emitting particles.
  55738. */
  55739. this.maxSize = 1;
  55740. /**
  55741. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  55742. */
  55743. this.minAngularSpeed = 0;
  55744. /**
  55745. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  55746. */
  55747. this.maxAngularSpeed = 0;
  55748. /**
  55749. * The layer mask we are rendering the particles through.
  55750. */
  55751. this.layerMask = 0x0FFFFFFF;
  55752. /**
  55753. * This can help using your own shader to render the particle system.
  55754. * The according effect will be created
  55755. */
  55756. this.customShader = null;
  55757. /**
  55758. * By default particle system starts as soon as they are created. This prevents the
  55759. * automatic start to happen and let you decide when to start emitting particles.
  55760. */
  55761. this.preventAutoStart = false;
  55762. /**
  55763. * Callback triggered when the particle animation is ending.
  55764. */
  55765. this.onAnimationEnd = null;
  55766. /**
  55767. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  55768. */
  55769. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  55770. /**
  55771. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  55772. * to override the particles.
  55773. */
  55774. this.forceDepthWrite = false;
  55775. /**
  55776. * You can use gravity if you want to give an orientation to your particles.
  55777. */
  55778. this.gravity = BABYLON.Vector3.Zero();
  55779. /**
  55780. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  55781. */
  55782. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55783. /**
  55784. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  55785. */
  55786. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55787. /**
  55788. * Color the particle will have at the end of its lifetime.
  55789. */
  55790. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  55791. /**
  55792. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  55793. */
  55794. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55795. /**
  55796. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  55797. */
  55798. this.spriteCellLoop = true;
  55799. /**
  55800. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  55801. */
  55802. this.spriteCellChangeSpeed = 0;
  55803. /**
  55804. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  55805. */
  55806. this.startSpriteCellID = 0;
  55807. /**
  55808. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  55809. */
  55810. this.endSpriteCellID = 0;
  55811. /**
  55812. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  55813. */
  55814. this.spriteCellWidth = 0;
  55815. /**
  55816. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  55817. */
  55818. this.spriteCellHeight = 0;
  55819. /**
  55820. * An event triggered when the system is disposed.
  55821. */
  55822. this.onDisposeObservable = new BABYLON.Observable();
  55823. this._particles = new Array();
  55824. this._stockParticles = new Array();
  55825. this._newPartsExcess = 0;
  55826. this._vertexBuffers = {};
  55827. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  55828. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  55829. this._scaledDirection = BABYLON.Vector3.Zero();
  55830. this._scaledGravity = BABYLON.Vector3.Zero();
  55831. this._currentRenderId = -1;
  55832. this._started = false;
  55833. this._stopped = false;
  55834. this._actualFrame = 0;
  55835. this._vertexBufferSize = 11;
  55836. // start of sub system methods
  55837. /**
  55838. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  55839. * Its lifetime will start back at 0.
  55840. */
  55841. this.recycleParticle = function (particle) {
  55842. var lastParticle = _this._particles.pop();
  55843. if (lastParticle !== particle) {
  55844. lastParticle.copyTo(particle);
  55845. }
  55846. _this._stockParticles.push(lastParticle);
  55847. };
  55848. this._createParticle = function () {
  55849. var particle;
  55850. if (_this._stockParticles.length !== 0) {
  55851. particle = _this._stockParticles.pop();
  55852. particle.age = 0;
  55853. particle.cellIndex = _this.startSpriteCellID;
  55854. }
  55855. else {
  55856. particle = new BABYLON.Particle(_this);
  55857. }
  55858. return particle;
  55859. };
  55860. this._emitFromParticle = function (particle) {
  55861. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  55862. return;
  55863. }
  55864. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  55865. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  55866. subSystem._rootParticleSystem = _this;
  55867. _this.activeSubSystems.push(subSystem);
  55868. subSystem.start();
  55869. };
  55870. this._appendParticleVertexes = null;
  55871. this.id = name;
  55872. this.name = name;
  55873. this._capacity = capacity;
  55874. this._epsilon = epsilon;
  55875. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  55876. if (isAnimationSheetEnabled) {
  55877. this._vertexBufferSize = 12;
  55878. }
  55879. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  55880. this._customEffect = customEffect;
  55881. scene.particleSystems.push(this);
  55882. this._createIndexBuffer();
  55883. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  55884. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  55885. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  55886. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  55887. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  55888. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  55889. if (this._isAnimationSheetEnabled) {
  55890. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  55891. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  55892. }
  55893. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  55894. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  55895. this._vertexBuffers["options"] = options;
  55896. // Default emitter type
  55897. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  55898. this.updateFunction = function (particles) {
  55899. for (var index = 0; index < particles.length; index++) {
  55900. var particle = particles[index];
  55901. particle.age += _this._scaledUpdateSpeed;
  55902. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  55903. _this._emitFromParticle(particle);
  55904. _this.recycleParticle(particle);
  55905. index--;
  55906. continue;
  55907. }
  55908. else {
  55909. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  55910. particle.color.addInPlace(_this._scaledColorStep);
  55911. if (particle.color.a < 0)
  55912. particle.color.a = 0;
  55913. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  55914. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  55915. particle.position.addInPlace(_this._scaledDirection);
  55916. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  55917. particle.direction.addInPlace(_this._scaledGravity);
  55918. if (_this._isAnimationSheetEnabled) {
  55919. particle.updateCellIndex(_this._scaledUpdateSpeed);
  55920. }
  55921. }
  55922. }
  55923. };
  55924. }
  55925. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  55926. /**
  55927. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55928. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55929. */
  55930. get: function () {
  55931. if (this.particleEmitterType.direction1) {
  55932. return this.particleEmitterType.direction1;
  55933. }
  55934. return BABYLON.Vector3.Zero();
  55935. },
  55936. set: function (value) {
  55937. if (this.particleEmitterType.direction1) {
  55938. this.particleEmitterType.direction1 = value;
  55939. }
  55940. },
  55941. enumerable: true,
  55942. configurable: true
  55943. });
  55944. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  55945. /**
  55946. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55947. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55948. */
  55949. get: function () {
  55950. if (this.particleEmitterType.direction2) {
  55951. return this.particleEmitterType.direction2;
  55952. }
  55953. return BABYLON.Vector3.Zero();
  55954. },
  55955. set: function (value) {
  55956. if (this.particleEmitterType.direction2) {
  55957. this.particleEmitterType.direction2 = value;
  55958. }
  55959. },
  55960. enumerable: true,
  55961. configurable: true
  55962. });
  55963. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  55964. /**
  55965. * 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.
  55966. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55967. */
  55968. get: function () {
  55969. if (this.particleEmitterType.minEmitBox) {
  55970. return this.particleEmitterType.minEmitBox;
  55971. }
  55972. return BABYLON.Vector3.Zero();
  55973. },
  55974. set: function (value) {
  55975. if (this.particleEmitterType.minEmitBox) {
  55976. this.particleEmitterType.minEmitBox = value;
  55977. }
  55978. },
  55979. enumerable: true,
  55980. configurable: true
  55981. });
  55982. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  55983. /**
  55984. * 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.
  55985. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55986. */
  55987. get: function () {
  55988. if (this.particleEmitterType.maxEmitBox) {
  55989. return this.particleEmitterType.maxEmitBox;
  55990. }
  55991. return BABYLON.Vector3.Zero();
  55992. },
  55993. set: function (value) {
  55994. if (this.particleEmitterType.maxEmitBox) {
  55995. this.particleEmitterType.maxEmitBox = value;
  55996. }
  55997. },
  55998. enumerable: true,
  55999. configurable: true
  56000. });
  56001. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  56002. /**
  56003. * Sets a callback that will be triggered when the system is disposed.
  56004. */
  56005. set: function (callback) {
  56006. if (this._onDisposeObserver) {
  56007. this.onDisposeObservable.remove(this._onDisposeObserver);
  56008. }
  56009. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  56010. },
  56011. enumerable: true,
  56012. configurable: true
  56013. });
  56014. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  56015. /**
  56016. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  56017. */
  56018. get: function () {
  56019. return this._isAnimationSheetEnabled;
  56020. },
  56021. enumerable: true,
  56022. configurable: true
  56023. });
  56024. Object.defineProperty(ParticleSystem.prototype, "particles", {
  56025. //end of Sub-emitter
  56026. /**
  56027. * Gets the current list of active particles
  56028. */
  56029. get: function () {
  56030. return this._particles;
  56031. },
  56032. enumerable: true,
  56033. configurable: true
  56034. });
  56035. /**
  56036. * Returns the string "ParticleSystem"
  56037. * @returns a string containing the class name
  56038. */
  56039. ParticleSystem.prototype.getClassName = function () {
  56040. return "ParticleSystem";
  56041. };
  56042. ParticleSystem.prototype._createIndexBuffer = function () {
  56043. var indices = [];
  56044. var index = 0;
  56045. for (var count = 0; count < this._capacity; count++) {
  56046. indices.push(index);
  56047. indices.push(index + 1);
  56048. indices.push(index + 2);
  56049. indices.push(index);
  56050. indices.push(index + 2);
  56051. indices.push(index + 3);
  56052. index += 4;
  56053. }
  56054. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  56055. };
  56056. /**
  56057. * Gets the maximum number of particles active at the same time.
  56058. * @returns The max number of active particles.
  56059. */
  56060. ParticleSystem.prototype.getCapacity = function () {
  56061. return this._capacity;
  56062. };
  56063. /**
  56064. * Gets Wether there are still active particles in the system.
  56065. * @returns True if it is alive, otherwise false.
  56066. */
  56067. ParticleSystem.prototype.isAlive = function () {
  56068. return this._alive;
  56069. };
  56070. /**
  56071. * Gets Wether the system has been started.
  56072. * @returns True if it has been started, otherwise false.
  56073. */
  56074. ParticleSystem.prototype.isStarted = function () {
  56075. return this._started;
  56076. };
  56077. /**
  56078. * Starts the particle system and begins to emit.
  56079. */
  56080. ParticleSystem.prototype.start = function () {
  56081. this._started = true;
  56082. this._stopped = false;
  56083. this._actualFrame = 0;
  56084. if (this.subEmitters && this.subEmitters.length != 0) {
  56085. this.activeSubSystems = new Array();
  56086. }
  56087. };
  56088. /**
  56089. * Stops the particle system.
  56090. * @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.
  56091. */
  56092. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  56093. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  56094. this._stopped = true;
  56095. if (stopSubEmitters) {
  56096. this._stopSubEmitters();
  56097. }
  56098. };
  56099. // animation sheet
  56100. /**
  56101. * Remove all active particles
  56102. */
  56103. ParticleSystem.prototype.reset = function () {
  56104. this._stockParticles = [];
  56105. this._particles = [];
  56106. };
  56107. /**
  56108. * @hidden (for internal use only)
  56109. */
  56110. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  56111. var offset = index * this._vertexBufferSize;
  56112. this._vertexData[offset] = particle.position.x;
  56113. this._vertexData[offset + 1] = particle.position.y;
  56114. this._vertexData[offset + 2] = particle.position.z;
  56115. this._vertexData[offset + 3] = particle.color.r;
  56116. this._vertexData[offset + 4] = particle.color.g;
  56117. this._vertexData[offset + 5] = particle.color.b;
  56118. this._vertexData[offset + 6] = particle.color.a;
  56119. this._vertexData[offset + 7] = particle.angle;
  56120. this._vertexData[offset + 8] = particle.size;
  56121. this._vertexData[offset + 9] = offsetX;
  56122. this._vertexData[offset + 10] = offsetY;
  56123. };
  56124. /**
  56125. * @hidden (for internal use only)
  56126. */
  56127. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  56128. if (offsetX === 0)
  56129. offsetX = this._epsilon;
  56130. else if (offsetX === 1)
  56131. offsetX = 1 - this._epsilon;
  56132. if (offsetY === 0)
  56133. offsetY = this._epsilon;
  56134. else if (offsetY === 1)
  56135. offsetY = 1 - this._epsilon;
  56136. var offset = index * this._vertexBufferSize;
  56137. this._vertexData[offset] = particle.position.x;
  56138. this._vertexData[offset + 1] = particle.position.y;
  56139. this._vertexData[offset + 2] = particle.position.z;
  56140. this._vertexData[offset + 3] = particle.color.r;
  56141. this._vertexData[offset + 4] = particle.color.g;
  56142. this._vertexData[offset + 5] = particle.color.b;
  56143. this._vertexData[offset + 6] = particle.color.a;
  56144. this._vertexData[offset + 7] = particle.angle;
  56145. this._vertexData[offset + 8] = particle.size;
  56146. this._vertexData[offset + 9] = offsetX;
  56147. this._vertexData[offset + 10] = offsetY;
  56148. this._vertexData[offset + 11] = particle.cellIndex;
  56149. };
  56150. ParticleSystem.prototype._stopSubEmitters = function () {
  56151. if (!this.activeSubSystems) {
  56152. return;
  56153. }
  56154. this.activeSubSystems.forEach(function (subSystem) {
  56155. subSystem.stop(true);
  56156. });
  56157. this.activeSubSystems = new Array();
  56158. };
  56159. ParticleSystem.prototype._removeFromRoot = function () {
  56160. if (!this._rootParticleSystem) {
  56161. return;
  56162. }
  56163. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  56164. if (index !== -1) {
  56165. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  56166. }
  56167. };
  56168. // end of sub system methods
  56169. ParticleSystem.prototype._update = function (newParticles) {
  56170. // Update current
  56171. this._alive = this._particles.length > 0;
  56172. this.updateFunction(this._particles);
  56173. // Add new ones
  56174. var worldMatrix;
  56175. if (this.emitter.position) {
  56176. var emitterMesh = this.emitter;
  56177. worldMatrix = emitterMesh.getWorldMatrix();
  56178. }
  56179. else {
  56180. var emitterPosition = this.emitter;
  56181. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  56182. }
  56183. var particle;
  56184. for (var index = 0; index < newParticles; index++) {
  56185. if (this._particles.length === this._capacity) {
  56186. break;
  56187. }
  56188. particle = this._createParticle();
  56189. this._particles.push(particle);
  56190. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  56191. if (this.startPositionFunction) {
  56192. this.startPositionFunction(worldMatrix, particle.position, particle);
  56193. }
  56194. else {
  56195. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  56196. }
  56197. if (this.startDirectionFunction) {
  56198. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  56199. }
  56200. else {
  56201. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  56202. }
  56203. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  56204. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  56205. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  56206. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  56207. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  56208. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  56209. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  56210. }
  56211. };
  56212. ParticleSystem.prototype._getEffect = function () {
  56213. if (this._customEffect) {
  56214. return this._customEffect;
  56215. }
  56216. ;
  56217. var defines = [];
  56218. if (this._scene.clipPlane) {
  56219. defines.push("#define CLIPPLANE");
  56220. }
  56221. if (this._isAnimationSheetEnabled) {
  56222. defines.push("#define ANIMATESHEET");
  56223. }
  56224. // Effect
  56225. var join = defines.join("\n");
  56226. if (this._cachedDefines !== join) {
  56227. this._cachedDefines = join;
  56228. var attributesNamesOrOptions;
  56229. var effectCreationOption;
  56230. if (this._isAnimationSheetEnabled) {
  56231. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  56232. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  56233. }
  56234. else {
  56235. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  56236. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  56237. }
  56238. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  56239. }
  56240. return this._effect;
  56241. };
  56242. /**
  56243. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  56244. */
  56245. ParticleSystem.prototype.animate = function () {
  56246. if (!this._started)
  56247. return;
  56248. var effect = this._getEffect();
  56249. // Check
  56250. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  56251. return;
  56252. if (this._currentRenderId === this._scene.getRenderId()) {
  56253. return;
  56254. }
  56255. this._currentRenderId = this._scene.getRenderId();
  56256. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  56257. // determine the number of particles we need to create
  56258. var newParticles;
  56259. if (this.manualEmitCount > -1) {
  56260. newParticles = this.manualEmitCount;
  56261. this._newPartsExcess = 0;
  56262. this.manualEmitCount = 0;
  56263. }
  56264. else {
  56265. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  56266. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  56267. }
  56268. if (this._newPartsExcess > 1.0) {
  56269. newParticles += this._newPartsExcess >> 0;
  56270. this._newPartsExcess -= this._newPartsExcess >> 0;
  56271. }
  56272. this._alive = false;
  56273. if (!this._stopped) {
  56274. this._actualFrame += this._scaledUpdateSpeed;
  56275. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  56276. this.stop();
  56277. }
  56278. else {
  56279. newParticles = 0;
  56280. }
  56281. this._update(newParticles);
  56282. // Stopped?
  56283. if (this._stopped) {
  56284. if (!this._alive) {
  56285. this._started = false;
  56286. if (this.onAnimationEnd) {
  56287. this.onAnimationEnd();
  56288. }
  56289. if (this.disposeOnStop) {
  56290. this._scene._toBeDisposed.push(this);
  56291. }
  56292. }
  56293. }
  56294. // Animation sheet
  56295. if (this._isAnimationSheetEnabled) {
  56296. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  56297. }
  56298. else {
  56299. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  56300. }
  56301. // Update VBO
  56302. var offset = 0;
  56303. for (var index = 0; index < this._particles.length; index++) {
  56304. var particle = this._particles[index];
  56305. this._appendParticleVertexes(offset, particle);
  56306. offset += 4;
  56307. }
  56308. if (this._vertexBuffer) {
  56309. this._vertexBuffer.update(this._vertexData);
  56310. }
  56311. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  56312. this.stop();
  56313. }
  56314. };
  56315. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  56316. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  56317. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  56318. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  56319. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  56320. };
  56321. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  56322. this._appendParticleVertex(offset++, particle, 0, 0);
  56323. this._appendParticleVertex(offset++, particle, 1, 0);
  56324. this._appendParticleVertex(offset++, particle, 1, 1);
  56325. this._appendParticleVertex(offset++, particle, 0, 1);
  56326. };
  56327. /**
  56328. * Rebuilds the particle system.
  56329. */
  56330. ParticleSystem.prototype.rebuild = function () {
  56331. this._createIndexBuffer();
  56332. if (this._vertexBuffer) {
  56333. this._vertexBuffer._rebuild();
  56334. }
  56335. };
  56336. /**
  56337. * Is this system ready to be used/rendered
  56338. * @return true if the system is ready
  56339. */
  56340. ParticleSystem.prototype.isReady = function () {
  56341. var effect = this._getEffect();
  56342. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  56343. return false;
  56344. }
  56345. return true;
  56346. };
  56347. /**
  56348. * Renders the particle system in its current state.
  56349. * @returns the current number of particles
  56350. */
  56351. ParticleSystem.prototype.render = function () {
  56352. var effect = this._getEffect();
  56353. // Check
  56354. if (!this.isReady() || !this._particles.length) {
  56355. return 0;
  56356. }
  56357. var engine = this._scene.getEngine();
  56358. // Render
  56359. engine.enableEffect(effect);
  56360. engine.setState(false);
  56361. var viewMatrix = this._scene.getViewMatrix();
  56362. effect.setTexture("diffuseSampler", this.particleTexture);
  56363. effect.setMatrix("view", viewMatrix);
  56364. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  56365. if (this._isAnimationSheetEnabled && this.particleTexture) {
  56366. var baseSize = this.particleTexture.getBaseSize();
  56367. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  56368. }
  56369. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  56370. if (this._scene.clipPlane) {
  56371. var clipPlane = this._scene.clipPlane;
  56372. var invView = viewMatrix.clone();
  56373. invView.invert();
  56374. effect.setMatrix("invView", invView);
  56375. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  56376. }
  56377. // VBOs
  56378. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  56379. // Draw order
  56380. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  56381. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  56382. }
  56383. else {
  56384. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  56385. }
  56386. if (this.forceDepthWrite) {
  56387. engine.setDepthWrite(true);
  56388. }
  56389. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  56390. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  56391. return this._particles.length;
  56392. };
  56393. /**
  56394. * Disposes the particle system and free the associated resources
  56395. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  56396. */
  56397. ParticleSystem.prototype.dispose = function (disposeTexture) {
  56398. if (disposeTexture === void 0) { disposeTexture = true; }
  56399. if (this._vertexBuffer) {
  56400. this._vertexBuffer.dispose();
  56401. this._vertexBuffer = null;
  56402. }
  56403. if (this._indexBuffer) {
  56404. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  56405. this._indexBuffer = null;
  56406. }
  56407. if (disposeTexture && this.particleTexture) {
  56408. this.particleTexture.dispose();
  56409. this.particleTexture = null;
  56410. }
  56411. this._removeFromRoot();
  56412. // Remove from scene
  56413. var index = this._scene.particleSystems.indexOf(this);
  56414. if (index > -1) {
  56415. this._scene.particleSystems.splice(index, 1);
  56416. }
  56417. // Callback
  56418. this.onDisposeObservable.notifyObservers(this);
  56419. this.onDisposeObservable.clear();
  56420. };
  56421. /**
  56422. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  56423. * @param radius The radius of the sphere to emit from
  56424. * @returns the emitter
  56425. */
  56426. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  56427. if (radius === void 0) { radius = 1; }
  56428. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  56429. this.particleEmitterType = particleEmitter;
  56430. return particleEmitter;
  56431. };
  56432. /**
  56433. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  56434. * @param radius The radius of the sphere to emit from
  56435. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  56436. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  56437. * @returns the emitter
  56438. */
  56439. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  56440. if (radius === void 0) { radius = 1; }
  56441. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  56442. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  56443. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  56444. this.particleEmitterType = particleEmitter;
  56445. return particleEmitter;
  56446. };
  56447. /**
  56448. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  56449. * @param radius The radius of the cone to emit from
  56450. * @param angle The base angle of the cone
  56451. * @returns the emitter
  56452. */
  56453. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  56454. if (radius === void 0) { radius = 1; }
  56455. if (angle === void 0) { angle = Math.PI / 4; }
  56456. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  56457. this.particleEmitterType = particleEmitter;
  56458. return particleEmitter;
  56459. };
  56460. // 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.
  56461. /**
  56462. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  56463. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  56464. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  56465. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56466. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56467. * @returns the emitter
  56468. */
  56469. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  56470. var particleEmitter = new BABYLON.BoxParticleEmitter();
  56471. this.particleEmitterType = particleEmitter;
  56472. this.direction1 = direction1;
  56473. this.direction2 = direction2;
  56474. this.minEmitBox = minEmitBox;
  56475. this.maxEmitBox = maxEmitBox;
  56476. return particleEmitter;
  56477. };
  56478. // Clone
  56479. /**
  56480. * Clones the particle system.
  56481. * @param name The name of the cloned object
  56482. * @param newEmitter The new emitter to use
  56483. * @returns the cloned particle system
  56484. */
  56485. ParticleSystem.prototype.clone = function (name, newEmitter) {
  56486. var custom = null;
  56487. var program = null;
  56488. if (this.customShader != null) {
  56489. program = this.customShader;
  56490. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56491. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56492. }
  56493. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  56494. result.customShader = program;
  56495. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  56496. if (newEmitter === undefined) {
  56497. newEmitter = this.emitter;
  56498. }
  56499. result.emitter = newEmitter;
  56500. if (this.particleTexture) {
  56501. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  56502. }
  56503. if (!this.preventAutoStart) {
  56504. result.start();
  56505. }
  56506. return result;
  56507. };
  56508. /**
  56509. * Serializes the particle system to a JSON object.
  56510. * @returns the JSON object
  56511. */
  56512. ParticleSystem.prototype.serialize = function () {
  56513. var serializationObject = {};
  56514. serializationObject.name = this.name;
  56515. serializationObject.id = this.id;
  56516. // Emitter
  56517. if (this.emitter.position) {
  56518. var emitterMesh = this.emitter;
  56519. serializationObject.emitterId = emitterMesh.id;
  56520. }
  56521. else {
  56522. var emitterPosition = this.emitter;
  56523. serializationObject.emitter = emitterPosition.asArray();
  56524. }
  56525. serializationObject.capacity = this.getCapacity();
  56526. if (this.particleTexture) {
  56527. serializationObject.textureName = this.particleTexture.name;
  56528. }
  56529. // Animations
  56530. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  56531. // Particle system
  56532. serializationObject.minAngularSpeed = this.minAngularSpeed;
  56533. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  56534. serializationObject.minSize = this.minSize;
  56535. serializationObject.maxSize = this.maxSize;
  56536. serializationObject.minEmitPower = this.minEmitPower;
  56537. serializationObject.maxEmitPower = this.maxEmitPower;
  56538. serializationObject.minLifeTime = this.minLifeTime;
  56539. serializationObject.maxLifeTime = this.maxLifeTime;
  56540. serializationObject.emitRate = this.emitRate;
  56541. serializationObject.minEmitBox = this.minEmitBox.asArray();
  56542. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  56543. serializationObject.gravity = this.gravity.asArray();
  56544. serializationObject.direction1 = this.direction1.asArray();
  56545. serializationObject.direction2 = this.direction2.asArray();
  56546. serializationObject.color1 = this.color1.asArray();
  56547. serializationObject.color2 = this.color2.asArray();
  56548. serializationObject.colorDead = this.colorDead.asArray();
  56549. serializationObject.updateSpeed = this.updateSpeed;
  56550. serializationObject.targetStopDuration = this.targetStopDuration;
  56551. serializationObject.textureMask = this.textureMask.asArray();
  56552. serializationObject.blendMode = this.blendMode;
  56553. serializationObject.customShader = this.customShader;
  56554. serializationObject.preventAutoStart = this.preventAutoStart;
  56555. serializationObject.startSpriteCellID = this.startSpriteCellID;
  56556. serializationObject.endSpriteCellID = this.endSpriteCellID;
  56557. serializationObject.spriteCellLoop = this.spriteCellLoop;
  56558. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  56559. serializationObject.spriteCellWidth = this.spriteCellWidth;
  56560. serializationObject.spriteCellHeight = this.spriteCellHeight;
  56561. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  56562. // Emitter
  56563. if (this.particleEmitterType) {
  56564. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  56565. }
  56566. return serializationObject;
  56567. };
  56568. /**
  56569. * Parses a JSON object to create a particle system.
  56570. * @param parsedParticleSystem The JSON object to parse
  56571. * @param scene The scene to create the particle system in
  56572. * @param rootUrl The root url to use to load external dependencies like texture
  56573. * @returns the Parsed particle system
  56574. */
  56575. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  56576. var name = parsedParticleSystem.name;
  56577. var custom = null;
  56578. var program = null;
  56579. if (parsedParticleSystem.customShader) {
  56580. program = parsedParticleSystem.customShader;
  56581. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56582. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56583. }
  56584. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  56585. particleSystem.customShader = program;
  56586. if (parsedParticleSystem.id) {
  56587. particleSystem.id = parsedParticleSystem.id;
  56588. }
  56589. // Auto start
  56590. if (parsedParticleSystem.preventAutoStart) {
  56591. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  56592. }
  56593. // Texture
  56594. if (parsedParticleSystem.textureName) {
  56595. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  56596. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  56597. }
  56598. // Emitter
  56599. if (parsedParticleSystem.emitterId) {
  56600. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  56601. }
  56602. else {
  56603. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  56604. }
  56605. // Animations
  56606. if (parsedParticleSystem.animations) {
  56607. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  56608. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  56609. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  56610. }
  56611. }
  56612. if (parsedParticleSystem.autoAnimate) {
  56613. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  56614. }
  56615. // Particle system
  56616. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  56617. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  56618. particleSystem.minSize = parsedParticleSystem.minSize;
  56619. particleSystem.maxSize = parsedParticleSystem.maxSize;
  56620. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  56621. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  56622. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  56623. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  56624. particleSystem.emitRate = parsedParticleSystem.emitRate;
  56625. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  56626. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  56627. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  56628. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  56629. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  56630. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  56631. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  56632. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  56633. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  56634. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  56635. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  56636. particleSystem.blendMode = parsedParticleSystem.blendMode;
  56637. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  56638. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  56639. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  56640. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  56641. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  56642. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  56643. if (!particleSystem.preventAutoStart) {
  56644. particleSystem.start();
  56645. }
  56646. return particleSystem;
  56647. };
  56648. /**
  56649. * Source color is added to the destination color without alpha affecting the result.
  56650. */
  56651. ParticleSystem.BLENDMODE_ONEONE = 0;
  56652. /**
  56653. * Blend current color and particle color using particle’s alpha.
  56654. */
  56655. ParticleSystem.BLENDMODE_STANDARD = 1;
  56656. return ParticleSystem;
  56657. }());
  56658. BABYLON.ParticleSystem = ParticleSystem;
  56659. })(BABYLON || (BABYLON = {}));
  56660. //# sourceMappingURL=babylon.particleSystem.js.map
  56661. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  56662. var BABYLON;
  56663. (function (BABYLON) {
  56664. /**
  56665. * Particle emitter emitting particles from the inside of a box.
  56666. * It emits the particles randomly between 2 given directions.
  56667. */
  56668. var BoxParticleEmitter = /** @class */ (function () {
  56669. /**
  56670. * Creates a new instance BoxParticleEmitter
  56671. */
  56672. function BoxParticleEmitter() {
  56673. /**
  56674. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56675. */
  56676. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  56677. /**
  56678. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56679. */
  56680. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  56681. /**
  56682. * 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.
  56683. */
  56684. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  56685. /**
  56686. * 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.
  56687. */
  56688. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  56689. }
  56690. /**
  56691. * Called by the particle System when the direction is computed for the created particle.
  56692. * @param emitPower is the power of the particle (speed)
  56693. * @param worldMatrix is the world matrix of the particle system
  56694. * @param directionToUpdate is the direction vector to update with the result
  56695. * @param particle is the particle we are computed the direction for
  56696. */
  56697. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56698. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56699. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56700. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56701. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  56702. };
  56703. /**
  56704. * Called by the particle System when the position is computed for the created particle.
  56705. * @param worldMatrix is the world matrix of the particle system
  56706. * @param positionToUpdate is the position vector to update with the result
  56707. * @param particle is the particle we are computed the position for
  56708. */
  56709. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56710. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  56711. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  56712. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  56713. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56714. };
  56715. /**
  56716. * Clones the current emitter and returns a copy of it
  56717. * @returns the new emitter
  56718. */
  56719. BoxParticleEmitter.prototype.clone = function () {
  56720. var newOne = new BoxParticleEmitter();
  56721. BABYLON.Tools.DeepCopy(this, newOne);
  56722. return newOne;
  56723. };
  56724. /**
  56725. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56726. * @param effect defines the update shader
  56727. */
  56728. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  56729. effect.setVector3("direction1", this.direction1);
  56730. effect.setVector3("direction2", this.direction2);
  56731. effect.setVector3("minEmitBox", this.minEmitBox);
  56732. effect.setVector3("maxEmitBox", this.maxEmitBox);
  56733. };
  56734. /**
  56735. * Returns a string to use to update the GPU particles update shader
  56736. * @returns a string containng the defines string
  56737. */
  56738. BoxParticleEmitter.prototype.getEffectDefines = function () {
  56739. return "#define BOXEMITTER";
  56740. };
  56741. /**
  56742. * Returns the string "BoxEmitter"
  56743. * @returns a string containing the class name
  56744. */
  56745. BoxParticleEmitter.prototype.getClassName = function () {
  56746. return "BoxEmitter";
  56747. };
  56748. /**
  56749. * Serializes the particle system to a JSON object.
  56750. * @returns the JSON object
  56751. */
  56752. BoxParticleEmitter.prototype.serialize = function () {
  56753. var serializationObject = {};
  56754. serializationObject.type = this.getClassName();
  56755. serializationObject.direction1 = this.direction1.asArray();
  56756. serializationObject.direction2 = this.direction2.asArray();
  56757. serializationObject.minEmitBox = this.minEmitBox.asArray();
  56758. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  56759. return serializationObject;
  56760. };
  56761. /**
  56762. * Parse properties from a JSON object
  56763. * @param serializationObject defines the JSON object
  56764. */
  56765. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  56766. this.direction1.copyFrom(serializationObject.direction1);
  56767. this.direction2.copyFrom(serializationObject.direction2);
  56768. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  56769. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  56770. };
  56771. return BoxParticleEmitter;
  56772. }());
  56773. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  56774. })(BABYLON || (BABYLON = {}));
  56775. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  56776. var BABYLON;
  56777. (function (BABYLON) {
  56778. /**
  56779. * Particle emitter emitting particles from the inside of a cone.
  56780. * It emits the particles alongside the cone volume from the base to the particle.
  56781. * The emission direction might be randomized.
  56782. */
  56783. var ConeParticleEmitter = /** @class */ (function () {
  56784. /**
  56785. * Creates a new instance ConeParticleEmitter
  56786. * @param radius the radius of the emission cone (1 by default)
  56787. * @param angles the cone base angle (PI by default)
  56788. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  56789. */
  56790. function ConeParticleEmitter(radius,
  56791. /**
  56792. * The radius of the emission cone.
  56793. */
  56794. angle,
  56795. /**
  56796. * The cone base angle.
  56797. */
  56798. directionRandomizer) {
  56799. if (radius === void 0) { radius = 1; }
  56800. if (angle === void 0) { angle = Math.PI; }
  56801. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56802. this.angle = angle;
  56803. this.directionRandomizer = directionRandomizer;
  56804. this.radius = radius;
  56805. }
  56806. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  56807. /**
  56808. * Gets the radius of the emission cone.
  56809. */
  56810. get: function () {
  56811. return this._radius;
  56812. },
  56813. /**
  56814. * Sets the radius of the emission cone.
  56815. */
  56816. set: function (value) {
  56817. this._radius = value;
  56818. if (this.angle !== 0) {
  56819. this._height = value / Math.tan(this.angle / 2);
  56820. }
  56821. else {
  56822. this._height = 1;
  56823. }
  56824. },
  56825. enumerable: true,
  56826. configurable: true
  56827. });
  56828. /**
  56829. * Called by the particle System when the direction is computed for the created particle.
  56830. * @param emitPower is the power of the particle (speed)
  56831. * @param worldMatrix is the world matrix of the particle system
  56832. * @param directionToUpdate is the direction vector to update with the result
  56833. * @param particle is the particle we are computed the direction for
  56834. */
  56835. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56836. if (this.angle === 0) {
  56837. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  56838. }
  56839. else {
  56840. // measure the direction Vector from the emitter to the particle.
  56841. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56842. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56843. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56844. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56845. direction.x += randX;
  56846. direction.y += randY;
  56847. direction.z += randZ;
  56848. direction.normalize();
  56849. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  56850. }
  56851. };
  56852. /**
  56853. * Called by the particle System when the position is computed for the created particle.
  56854. * @param worldMatrix is the world matrix of the particle system
  56855. * @param positionToUpdate is the position vector to update with the result
  56856. * @param particle is the particle we are computed the position for
  56857. */
  56858. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56859. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  56860. var h = BABYLON.Scalar.RandomRange(0, 1);
  56861. // Better distribution in a cone at normal angles.
  56862. h = 1 - h * h;
  56863. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  56864. radius = radius * h;
  56865. var randX = radius * Math.sin(s);
  56866. var randZ = radius * Math.cos(s);
  56867. var randY = h * this._height;
  56868. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56869. };
  56870. /**
  56871. * Clones the current emitter and returns a copy of it
  56872. * @returns the new emitter
  56873. */
  56874. ConeParticleEmitter.prototype.clone = function () {
  56875. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  56876. BABYLON.Tools.DeepCopy(this, newOne);
  56877. return newOne;
  56878. };
  56879. /**
  56880. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56881. * @param effect defines the update shader
  56882. */
  56883. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  56884. effect.setFloat("radius", this.radius);
  56885. effect.setFloat("angle", this.angle);
  56886. effect.setFloat("height", this._height);
  56887. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56888. };
  56889. /**
  56890. * Returns a string to use to update the GPU particles update shader
  56891. * @returns a string containng the defines string
  56892. */
  56893. ConeParticleEmitter.prototype.getEffectDefines = function () {
  56894. return "#define CONEEMITTER";
  56895. };
  56896. /**
  56897. * Returns the string "BoxEmitter"
  56898. * @returns a string containing the class name
  56899. */
  56900. ConeParticleEmitter.prototype.getClassName = function () {
  56901. return "ConeEmitter";
  56902. };
  56903. /**
  56904. * Serializes the particle system to a JSON object.
  56905. * @returns the JSON object
  56906. */
  56907. ConeParticleEmitter.prototype.serialize = function () {
  56908. var serializationObject = {};
  56909. serializationObject.type = this.getClassName();
  56910. serializationObject.radius = this.radius;
  56911. serializationObject.angle = this.angle;
  56912. serializationObject.directionRandomizer = this.directionRandomizer;
  56913. return serializationObject;
  56914. };
  56915. /**
  56916. * Parse properties from a JSON object
  56917. * @param serializationObject defines the JSON object
  56918. */
  56919. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  56920. this.radius = serializationObject.radius;
  56921. this.angle = serializationObject.angle;
  56922. this.directionRandomizer = serializationObject.directionRandomizer;
  56923. };
  56924. return ConeParticleEmitter;
  56925. }());
  56926. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  56927. })(BABYLON || (BABYLON = {}));
  56928. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  56929. var BABYLON;
  56930. (function (BABYLON) {
  56931. /**
  56932. * Particle emitter emitting particles from the inside of a sphere.
  56933. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  56934. */
  56935. var SphereParticleEmitter = /** @class */ (function () {
  56936. /**
  56937. * Creates a new instance SphereParticleEmitter
  56938. * @param radius the radius of the emission sphere (1 by default)
  56939. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  56940. */
  56941. function SphereParticleEmitter(
  56942. /**
  56943. * The radius of the emission sphere.
  56944. */
  56945. radius,
  56946. /**
  56947. * How much to randomize the particle direction [0-1].
  56948. */
  56949. directionRandomizer) {
  56950. if (radius === void 0) { radius = 1; }
  56951. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56952. this.radius = radius;
  56953. this.directionRandomizer = directionRandomizer;
  56954. }
  56955. /**
  56956. * Called by the particle System when the direction is computed for the created particle.
  56957. * @param emitPower is the power of the particle (speed)
  56958. * @param worldMatrix is the world matrix of the particle system
  56959. * @param directionToUpdate is the direction vector to update with the result
  56960. * @param particle is the particle we are computed the direction for
  56961. */
  56962. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56963. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56964. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56965. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56966. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56967. direction.x += randX;
  56968. direction.y += randY;
  56969. direction.z += randZ;
  56970. direction.normalize();
  56971. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  56972. };
  56973. /**
  56974. * Called by the particle System when the position is computed for the created particle.
  56975. * @param worldMatrix is the world matrix of the particle system
  56976. * @param positionToUpdate is the position vector to update with the result
  56977. * @param particle is the particle we are computed the position for
  56978. */
  56979. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56980. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  56981. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  56982. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  56983. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  56984. var randY = randRadius * Math.cos(theta);
  56985. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  56986. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56987. };
  56988. /**
  56989. * Clones the current emitter and returns a copy of it
  56990. * @returns the new emitter
  56991. */
  56992. SphereParticleEmitter.prototype.clone = function () {
  56993. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  56994. BABYLON.Tools.DeepCopy(this, newOne);
  56995. return newOne;
  56996. };
  56997. /**
  56998. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56999. * @param effect defines the update shader
  57000. */
  57001. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  57002. effect.setFloat("radius", this.radius);
  57003. effect.setFloat("directionRandomizer", this.directionRandomizer);
  57004. };
  57005. /**
  57006. * Returns a string to use to update the GPU particles update shader
  57007. * @returns a string containng the defines string
  57008. */
  57009. SphereParticleEmitter.prototype.getEffectDefines = function () {
  57010. return "#define SPHEREEMITTER";
  57011. };
  57012. /**
  57013. * Returns the string "SphereParticleEmitter"
  57014. * @returns a string containing the class name
  57015. */
  57016. SphereParticleEmitter.prototype.getClassName = function () {
  57017. return "SphereParticleEmitter";
  57018. };
  57019. /**
  57020. * Serializes the particle system to a JSON object.
  57021. * @returns the JSON object
  57022. */
  57023. SphereParticleEmitter.prototype.serialize = function () {
  57024. var serializationObject = {};
  57025. serializationObject.type = this.getClassName();
  57026. serializationObject.radius = this.radius;
  57027. serializationObject.directionRandomizer = this.directionRandomizer;
  57028. return serializationObject;
  57029. };
  57030. /**
  57031. * Parse properties from a JSON object
  57032. * @param serializationObject defines the JSON object
  57033. */
  57034. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  57035. this.radius = serializationObject.radius;
  57036. this.directionRandomizer = serializationObject.directionRandomizer;
  57037. };
  57038. return SphereParticleEmitter;
  57039. }());
  57040. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  57041. /**
  57042. * Particle emitter emitting particles from the inside of a sphere.
  57043. * It emits the particles randomly between two vectors.
  57044. */
  57045. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  57046. __extends(SphereDirectedParticleEmitter, _super);
  57047. /**
  57048. * Creates a new instance SphereDirectedParticleEmitter
  57049. * @param radius the radius of the emission sphere (1 by default)
  57050. * @param direction1 the min limit of the emission direction (up vector by default)
  57051. * @param direction2 the max limit of the emission direction (up vector by default)
  57052. */
  57053. function SphereDirectedParticleEmitter(radius,
  57054. /**
  57055. * The min limit of the emission direction.
  57056. */
  57057. direction1,
  57058. /**
  57059. * The max limit of the emission direction.
  57060. */
  57061. direction2) {
  57062. if (radius === void 0) { radius = 1; }
  57063. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  57064. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  57065. var _this = _super.call(this, radius) || this;
  57066. _this.direction1 = direction1;
  57067. _this.direction2 = direction2;
  57068. return _this;
  57069. }
  57070. /**
  57071. * Called by the particle System when the direction is computed for the created particle.
  57072. * @param emitPower is the power of the particle (speed)
  57073. * @param worldMatrix is the world matrix of the particle system
  57074. * @param directionToUpdate is the direction vector to update with the result
  57075. * @param particle is the particle we are computed the direction for
  57076. */
  57077. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  57078. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  57079. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  57080. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  57081. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  57082. };
  57083. /**
  57084. * Clones the current emitter and returns a copy of it
  57085. * @returns the new emitter
  57086. */
  57087. SphereDirectedParticleEmitter.prototype.clone = function () {
  57088. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  57089. BABYLON.Tools.DeepCopy(this, newOne);
  57090. return newOne;
  57091. };
  57092. /**
  57093. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57094. * @param effect defines the update shader
  57095. */
  57096. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  57097. effect.setFloat("radius", this.radius);
  57098. effect.setVector3("direction1", this.direction1);
  57099. effect.setVector3("direction2", this.direction2);
  57100. };
  57101. /**
  57102. * Returns a string to use to update the GPU particles update shader
  57103. * @returns a string containng the defines string
  57104. */
  57105. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  57106. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  57107. };
  57108. /**
  57109. * Returns the string "SphereDirectedParticleEmitter"
  57110. * @returns a string containing the class name
  57111. */
  57112. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  57113. return "SphereDirectedParticleEmitter";
  57114. };
  57115. /**
  57116. * Serializes the particle system to a JSON object.
  57117. * @returns the JSON object
  57118. */
  57119. SphereDirectedParticleEmitter.prototype.serialize = function () {
  57120. var serializationObject = _super.prototype.serialize.call(this);
  57121. serializationObject.direction1 = this.direction1.asArray();
  57122. serializationObject.direction2 = this.direction2.asArray();
  57123. return serializationObject;
  57124. };
  57125. /**
  57126. * Parse properties from a JSON object
  57127. * @param serializationObject defines the JSON object
  57128. */
  57129. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  57130. _super.prototype.parse.call(this, serializationObject);
  57131. this.direction1.copyFrom(serializationObject.direction1);
  57132. this.direction2.copyFrom(serializationObject.direction2);
  57133. };
  57134. return SphereDirectedParticleEmitter;
  57135. }(SphereParticleEmitter));
  57136. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  57137. })(BABYLON || (BABYLON = {}));
  57138. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  57139. var __assign = (this && this.__assign) || Object.assign || function(t) {
  57140. for (var s, i = 1, n = arguments.length; i < n; i++) {
  57141. s = arguments[i];
  57142. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  57143. t[p] = s[p];
  57144. }
  57145. return t;
  57146. };
  57147. var BABYLON;
  57148. (function (BABYLON) {
  57149. /**
  57150. * This represents a GPU particle system in Babylon
  57151. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  57152. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  57153. */
  57154. var GPUParticleSystem = /** @class */ (function () {
  57155. /**
  57156. * Instantiates a GPU particle system.
  57157. * 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.
  57158. * @param name The name of the particle system
  57159. * @param capacity The max number of particles alive at the same time
  57160. * @param scene The scene the particle system belongs to
  57161. */
  57162. function GPUParticleSystem(name, options, scene) {
  57163. /**
  57164. * The emitter represents the Mesh or position we are attaching the particle system to.
  57165. */
  57166. this.emitter = null;
  57167. /**
  57168. * The rendering group used by the Particle system to chose when to render.
  57169. */
  57170. this.renderingGroupId = 0;
  57171. /**
  57172. * The layer mask we are rendering the particles through.
  57173. */
  57174. this.layerMask = 0x0FFFFFFF;
  57175. this._targetIndex = 0;
  57176. this._currentRenderId = -1;
  57177. this._started = false;
  57178. this._stopped = false;
  57179. this._timeDelta = 0;
  57180. this._attributesStrideSize = 14;
  57181. this._actualFrame = 0;
  57182. /**
  57183. * List of animations used by the particle system.
  57184. */
  57185. this.animations = [];
  57186. /**
  57187. * An event triggered when the system is disposed.
  57188. */
  57189. this.onDisposeObservable = new BABYLON.Observable();
  57190. /**
  57191. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  57192. */
  57193. this.updateSpeed = 0.01;
  57194. /**
  57195. * The amount of time the particle system is running (depends of the overall update speed).
  57196. */
  57197. this.targetStopDuration = 0;
  57198. /**
  57199. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  57200. */
  57201. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  57202. /**
  57203. * Minimum life time of emitting particles.
  57204. */
  57205. this.minLifeTime = 1;
  57206. /**
  57207. * Maximum life time of emitting particles.
  57208. */
  57209. this.maxLifeTime = 1;
  57210. /**
  57211. * Minimum Size of emitting particles.
  57212. */
  57213. this.minSize = 1;
  57214. /**
  57215. * Maximum Size of emitting particles.
  57216. */
  57217. this.maxSize = 1;
  57218. /**
  57219. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57220. */
  57221. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57222. /**
  57223. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57224. */
  57225. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57226. /**
  57227. * Color the particle will have at the end of its lifetime.
  57228. */
  57229. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  57230. /**
  57231. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  57232. */
  57233. this.emitRate = 100;
  57234. /**
  57235. * You can use gravity if you want to give an orientation to your particles.
  57236. */
  57237. this.gravity = BABYLON.Vector3.Zero();
  57238. /**
  57239. * Minimum power of emitting particles.
  57240. */
  57241. this.minEmitPower = 1;
  57242. /**
  57243. * Maximum power of emitting particles.
  57244. */
  57245. this.maxEmitPower = 1;
  57246. /**
  57247. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  57248. * to override the particles.
  57249. */
  57250. this.forceDepthWrite = false;
  57251. this.id = name;
  57252. this.name = name;
  57253. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  57254. this._engine = this._scene.getEngine();
  57255. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  57256. this._capacity = fullOptions.capacity;
  57257. this._activeCount = fullOptions.capacity;
  57258. this._currentActiveCount = 0;
  57259. this._scene.particleSystems.push(this);
  57260. this._updateEffectOptions = {
  57261. attributes: ["position", "age", "life", "seed", "size", "color", "direction"],
  57262. uniformsNames: ["currentCount", "timeDelta", "generalRandoms", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "gravity", "emitPower",
  57263. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "angle", "stopFactor"],
  57264. uniformBuffersNames: [],
  57265. samplers: ["randomSampler"],
  57266. defines: "",
  57267. fallbacks: null,
  57268. onCompiled: null,
  57269. onError: null,
  57270. indexParameters: null,
  57271. maxSimultaneousLights: 0,
  57272. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection"]
  57273. };
  57274. // Random data
  57275. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  57276. var d = [];
  57277. for (var i = 0; i < maxTextureSize; ++i) {
  57278. d.push(Math.random());
  57279. d.push(Math.random());
  57280. d.push(Math.random());
  57281. d.push(Math.random());
  57282. }
  57283. this._randomTexture = new BABYLON.RawTexture(new Float32Array(d), maxTextureSize, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA32F, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, BABYLON.Engine.TEXTURETYPE_FLOAT);
  57284. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57285. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57286. this._randomTextureSize = maxTextureSize;
  57287. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  57288. }
  57289. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  57290. /**
  57291. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  57292. */
  57293. get: function () {
  57294. if (!BABYLON.Engine.LastCreatedEngine) {
  57295. return false;
  57296. }
  57297. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  57298. },
  57299. enumerable: true,
  57300. configurable: true
  57301. });
  57302. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  57303. /**
  57304. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57305. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57306. */
  57307. get: function () {
  57308. if (this.particleEmitterType.direction1) {
  57309. return this.particleEmitterType.direction1;
  57310. }
  57311. return BABYLON.Vector3.Zero();
  57312. },
  57313. set: function (value) {
  57314. if (this.particleEmitterType.direction1) {
  57315. this.particleEmitterType.direction1 = value;
  57316. }
  57317. },
  57318. enumerable: true,
  57319. configurable: true
  57320. });
  57321. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  57322. /**
  57323. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57324. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57325. */
  57326. get: function () {
  57327. if (this.particleEmitterType.direction2) {
  57328. return this.particleEmitterType.direction2;
  57329. }
  57330. return BABYLON.Vector3.Zero();
  57331. },
  57332. set: function (value) {
  57333. if (this.particleEmitterType.direction2) {
  57334. this.particleEmitterType.direction2 = value;
  57335. }
  57336. },
  57337. enumerable: true,
  57338. configurable: true
  57339. });
  57340. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  57341. /**
  57342. * 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.
  57343. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57344. */
  57345. get: function () {
  57346. if (this.particleEmitterType.minEmitBox) {
  57347. return this.particleEmitterType.minEmitBox;
  57348. }
  57349. return BABYLON.Vector3.Zero();
  57350. },
  57351. set: function (value) {
  57352. if (this.particleEmitterType.minEmitBox) {
  57353. this.particleEmitterType.minEmitBox = value;
  57354. }
  57355. },
  57356. enumerable: true,
  57357. configurable: true
  57358. });
  57359. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  57360. /**
  57361. * 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.
  57362. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57363. */
  57364. get: function () {
  57365. if (this.particleEmitterType.maxEmitBox) {
  57366. return this.particleEmitterType.maxEmitBox;
  57367. }
  57368. return BABYLON.Vector3.Zero();
  57369. },
  57370. set: function (value) {
  57371. if (this.particleEmitterType.maxEmitBox) {
  57372. this.particleEmitterType.maxEmitBox = value;
  57373. }
  57374. },
  57375. enumerable: true,
  57376. configurable: true
  57377. });
  57378. /**
  57379. * Gets the maximum number of particles active at the same time.
  57380. * @returns The max number of active particles.
  57381. */
  57382. GPUParticleSystem.prototype.getCapacity = function () {
  57383. return this._capacity;
  57384. };
  57385. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  57386. /**
  57387. * Gets or set the number of active particles
  57388. */
  57389. get: function () {
  57390. return this._activeCount;
  57391. },
  57392. set: function (value) {
  57393. this._activeCount = Math.min(value, this._capacity);
  57394. },
  57395. enumerable: true,
  57396. configurable: true
  57397. });
  57398. /**
  57399. * Is this system ready to be used/rendered
  57400. * @return true if the system is ready
  57401. */
  57402. GPUParticleSystem.prototype.isReady = function () {
  57403. if (!this._updateEffect) {
  57404. this._recreateUpdateEffect();
  57405. this._recreateRenderEffect();
  57406. return false;
  57407. }
  57408. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  57409. return false;
  57410. }
  57411. return true;
  57412. };
  57413. /**
  57414. * Gets Wether the system has been started.
  57415. * @returns True if it has been started, otherwise false.
  57416. */
  57417. GPUParticleSystem.prototype.isStarted = function () {
  57418. return this._started;
  57419. };
  57420. /**
  57421. * Starts the particle system and begins to emit.
  57422. */
  57423. GPUParticleSystem.prototype.start = function () {
  57424. this._started = true;
  57425. this._stopped = false;
  57426. };
  57427. /**
  57428. * Stops the particle system.
  57429. */
  57430. GPUParticleSystem.prototype.stop = function () {
  57431. this._stopped = true;
  57432. };
  57433. /**
  57434. * Remove all active particles
  57435. */
  57436. GPUParticleSystem.prototype.reset = function () {
  57437. this._releaseBuffers();
  57438. this._releaseVAOs();
  57439. this._currentActiveCount = 0;
  57440. this._targetIndex = 0;
  57441. };
  57442. /**
  57443. * Returns the string "GPUParticleSystem"
  57444. * @returns a string containing the class name
  57445. */
  57446. GPUParticleSystem.prototype.getClassName = function () {
  57447. return "GPUParticleSystem";
  57448. };
  57449. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  57450. var updateVertexBuffers = {};
  57451. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  57452. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  57453. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  57454. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  57455. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1);
  57456. updateVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4);
  57457. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 11, 3);
  57458. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  57459. this._engine.bindArrayBuffer(null);
  57460. return vao;
  57461. };
  57462. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  57463. var renderVertexBuffers = {};
  57464. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  57465. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  57466. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  57467. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1, this._attributesStrideSize, true);
  57468. renderVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4, this._attributesStrideSize, true);
  57469. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  57470. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  57471. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  57472. this._engine.bindArrayBuffer(null);
  57473. return vao;
  57474. };
  57475. GPUParticleSystem.prototype._initialize = function (force) {
  57476. if (force === void 0) { force = false; }
  57477. if (this._buffer0 && !force) {
  57478. return;
  57479. }
  57480. var engine = this._scene.getEngine();
  57481. var data = new Array();
  57482. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  57483. // position
  57484. data.push(0.0);
  57485. data.push(0.0);
  57486. data.push(0.0);
  57487. // Age and life
  57488. data.push(0.0); // create the particle as a dead one to create a new one at start
  57489. data.push(0.0);
  57490. // Seed
  57491. data.push(Math.random());
  57492. // Size
  57493. data.push(0.0);
  57494. // color
  57495. data.push(0.0);
  57496. data.push(0.0);
  57497. data.push(0.0);
  57498. data.push(0.0);
  57499. // direction
  57500. data.push(0.0);
  57501. data.push(0.0);
  57502. data.push(0.0);
  57503. }
  57504. // Sprite data
  57505. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  57506. -0.5, 0.5, 0, 1,
  57507. -0.5, -0.5, 0, 0,
  57508. 0.5, -0.5, 1, 0]);
  57509. // Buffers
  57510. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57511. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57512. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  57513. // Update VAO
  57514. this._updateVAO = [];
  57515. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  57516. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  57517. // Render VAO
  57518. this._renderVAO = [];
  57519. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  57520. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  57521. // Links
  57522. this._sourceBuffer = this._buffer0;
  57523. this._targetBuffer = this._buffer1;
  57524. };
  57525. /** @hidden */
  57526. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  57527. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  57528. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  57529. return;
  57530. }
  57531. this._updateEffectOptions.defines = defines;
  57532. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  57533. };
  57534. /** @hidden */
  57535. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  57536. var defines = "";
  57537. if (this._scene.clipPlane) {
  57538. defines = "\n#define CLIPPLANE";
  57539. }
  57540. if (this._renderEffect && this._renderEffect.defines === defines) {
  57541. return;
  57542. }
  57543. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler"], this._scene.getEngine(), defines);
  57544. };
  57545. /**
  57546. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  57547. */
  57548. GPUParticleSystem.prototype.animate = function () {
  57549. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  57550. this._actualFrame += this._timeDelta;
  57551. if (!this._stopped) {
  57552. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  57553. this.stop();
  57554. }
  57555. }
  57556. };
  57557. /**
  57558. * Renders the particle system in its current state.
  57559. * @returns the current number of particles
  57560. */
  57561. GPUParticleSystem.prototype.render = function () {
  57562. if (!this._started) {
  57563. return 0;
  57564. }
  57565. this._recreateUpdateEffect();
  57566. this._recreateRenderEffect();
  57567. if (!this.isReady()) {
  57568. return 0;
  57569. }
  57570. if (this._currentRenderId === this._scene.getRenderId()) {
  57571. return 0;
  57572. }
  57573. this._currentRenderId = this._scene.getRenderId();
  57574. // Get everything ready to render
  57575. this._initialize();
  57576. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + (this.emitRate * this._timeDelta) | 0);
  57577. // Enable update effect
  57578. this._engine.enableEffect(this._updateEffect);
  57579. this._engine.setState(false);
  57580. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  57581. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  57582. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  57583. this._updateEffect.setFloat3("generalRandoms", Math.random(), Math.random(), Math.random());
  57584. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  57585. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  57586. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  57587. this._updateEffect.setDirectColor4("color1", this.color1);
  57588. this._updateEffect.setDirectColor4("color2", this.color2);
  57589. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  57590. this._updateEffect.setVector3("gravity", this.gravity);
  57591. if (this.particleEmitterType) {
  57592. this.particleEmitterType.applyToShader(this._updateEffect);
  57593. }
  57594. var emitterWM;
  57595. if (this.emitter.position) {
  57596. var emitterMesh = this.emitter;
  57597. emitterWM = emitterMesh.getWorldMatrix();
  57598. }
  57599. else {
  57600. var emitterPosition = this.emitter;
  57601. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  57602. }
  57603. this._updateEffect.setMatrix("emitterWM", emitterWM);
  57604. // Bind source VAO
  57605. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  57606. // Update
  57607. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  57608. this._engine.setRasterizerState(false);
  57609. this._engine.beginTransformFeedback();
  57610. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  57611. this._engine.endTransformFeedback();
  57612. this._engine.setRasterizerState(true);
  57613. this._engine.bindTransformFeedbackBuffer(null);
  57614. // Enable render effect
  57615. this._engine.enableEffect(this._renderEffect);
  57616. var viewMatrix = this._scene.getViewMatrix();
  57617. this._renderEffect.setMatrix("view", viewMatrix);
  57618. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  57619. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  57620. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  57621. if (this._scene.clipPlane) {
  57622. var clipPlane = this._scene.clipPlane;
  57623. var invView = viewMatrix.clone();
  57624. invView.invert();
  57625. this._renderEffect.setMatrix("invView", invView);
  57626. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  57627. }
  57628. // Draw order
  57629. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  57630. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  57631. }
  57632. else {
  57633. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  57634. }
  57635. if (this.forceDepthWrite) {
  57636. this._engine.setDepthWrite(true);
  57637. }
  57638. // Bind source VAO
  57639. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  57640. // Render
  57641. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  57642. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  57643. // Switch VAOs
  57644. this._targetIndex++;
  57645. if (this._targetIndex === 2) {
  57646. this._targetIndex = 0;
  57647. }
  57648. // Switch buffers
  57649. var tmpBuffer = this._sourceBuffer;
  57650. this._sourceBuffer = this._targetBuffer;
  57651. this._targetBuffer = tmpBuffer;
  57652. return this._currentActiveCount;
  57653. };
  57654. /**
  57655. * Rebuilds the particle system
  57656. */
  57657. GPUParticleSystem.prototype.rebuild = function () {
  57658. this._initialize(true);
  57659. };
  57660. GPUParticleSystem.prototype._releaseBuffers = function () {
  57661. if (this._buffer0) {
  57662. this._buffer0.dispose();
  57663. this._buffer0 = null;
  57664. }
  57665. if (this._buffer1) {
  57666. this._buffer1.dispose();
  57667. this._buffer1 = null;
  57668. }
  57669. if (this._spriteBuffer) {
  57670. this._spriteBuffer.dispose();
  57671. this._spriteBuffer = null;
  57672. }
  57673. };
  57674. GPUParticleSystem.prototype._releaseVAOs = function () {
  57675. if (!this._updateVAO) {
  57676. return;
  57677. }
  57678. for (var index = 0; index < this._updateVAO.length; index++) {
  57679. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  57680. }
  57681. this._updateVAO = [];
  57682. for (var index = 0; index < this._renderVAO.length; index++) {
  57683. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  57684. }
  57685. this._renderVAO = [];
  57686. };
  57687. /**
  57688. * Disposes the particle system and free the associated resources
  57689. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  57690. */
  57691. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  57692. if (disposeTexture === void 0) { disposeTexture = true; }
  57693. var index = this._scene.particleSystems.indexOf(this);
  57694. if (index > -1) {
  57695. this._scene.particleSystems.splice(index, 1);
  57696. }
  57697. this._releaseBuffers();
  57698. this._releaseVAOs();
  57699. if (this._randomTexture) {
  57700. this._randomTexture.dispose();
  57701. this._randomTexture = null;
  57702. }
  57703. if (disposeTexture && this.particleTexture) {
  57704. this.particleTexture.dispose();
  57705. this.particleTexture = null;
  57706. }
  57707. // Callback
  57708. this.onDisposeObservable.notifyObservers(this);
  57709. this.onDisposeObservable.clear();
  57710. };
  57711. /**
  57712. * Clones the particle system.
  57713. * @param name The name of the cloned object
  57714. * @param newEmitter The new emitter to use
  57715. * @returns the cloned particle system
  57716. */
  57717. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  57718. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  57719. BABYLON.Tools.DeepCopy(this, result);
  57720. if (newEmitter === undefined) {
  57721. newEmitter = this.emitter;
  57722. }
  57723. result.emitter = newEmitter;
  57724. if (this.particleTexture) {
  57725. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  57726. }
  57727. return result;
  57728. };
  57729. /**
  57730. * Serializes the particle system to a JSON object.
  57731. * @returns the JSON object
  57732. */
  57733. GPUParticleSystem.prototype.serialize = function () {
  57734. var serializationObject = {};
  57735. serializationObject.name = this.name;
  57736. serializationObject.id = this.id;
  57737. // Emitter
  57738. if (this.emitter.position) {
  57739. var emitterMesh = this.emitter;
  57740. serializationObject.emitterId = emitterMesh.id;
  57741. }
  57742. else {
  57743. var emitterPosition = this.emitter;
  57744. serializationObject.emitter = emitterPosition.asArray();
  57745. }
  57746. serializationObject.capacity = this.getCapacity();
  57747. if (this.particleTexture) {
  57748. serializationObject.textureName = this.particleTexture.name;
  57749. }
  57750. // Animations
  57751. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  57752. // Particle system
  57753. serializationObject.activeParticleCount = this.activeParticleCount;
  57754. serializationObject.randomTextureSize = this._randomTextureSize;
  57755. serializationObject.minSize = this.minSize;
  57756. serializationObject.maxSize = this.maxSize;
  57757. serializationObject.minEmitPower = this.minEmitPower;
  57758. serializationObject.maxEmitPower = this.maxEmitPower;
  57759. serializationObject.minLifeTime = this.minLifeTime;
  57760. serializationObject.maxLifeTime = this.maxLifeTime;
  57761. serializationObject.emitRate = this.emitRate;
  57762. serializationObject.gravity = this.gravity.asArray();
  57763. serializationObject.color1 = this.color1.asArray();
  57764. serializationObject.color2 = this.color2.asArray();
  57765. serializationObject.colorDead = this.colorDead.asArray();
  57766. serializationObject.updateSpeed = this.updateSpeed;
  57767. serializationObject.targetStopDuration = this.targetStopDuration;
  57768. serializationObject.blendMode = this.blendMode;
  57769. // Emitter
  57770. if (this.particleEmitterType) {
  57771. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  57772. }
  57773. return serializationObject;
  57774. };
  57775. /**
  57776. * Parses a JSON object to create a GPU particle system.
  57777. * @param parsedParticleSystem The JSON object to parse
  57778. * @param scene The scene to create the particle system in
  57779. * @param rootUrl The root url to use to load external dependencies like texture
  57780. * @returns the parsed GPU particle system
  57781. */
  57782. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  57783. var name = parsedParticleSystem.name;
  57784. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  57785. if (parsedParticleSystem.id) {
  57786. particleSystem.id = parsedParticleSystem.id;
  57787. }
  57788. // Texture
  57789. if (parsedParticleSystem.textureName) {
  57790. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  57791. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  57792. }
  57793. // Emitter
  57794. if (parsedParticleSystem.emitterId) {
  57795. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  57796. }
  57797. else {
  57798. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  57799. }
  57800. // Animations
  57801. if (parsedParticleSystem.animations) {
  57802. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  57803. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  57804. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  57805. }
  57806. }
  57807. // Particle system
  57808. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  57809. particleSystem.minSize = parsedParticleSystem.minSize;
  57810. particleSystem.maxSize = parsedParticleSystem.maxSize;
  57811. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  57812. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  57813. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  57814. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  57815. particleSystem.emitRate = parsedParticleSystem.emitRate;
  57816. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  57817. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  57818. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  57819. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  57820. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  57821. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  57822. particleSystem.blendMode = parsedParticleSystem.blendMode;
  57823. // Emitter
  57824. if (parsedParticleSystem.particleEmitterType) {
  57825. var emitterType = void 0;
  57826. switch (parsedParticleSystem.particleEmitterType.type) {
  57827. case "SphereEmitter":
  57828. emitterType = new BABYLON.SphereParticleEmitter();
  57829. break;
  57830. case "SphereDirectedParticleEmitter":
  57831. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  57832. break;
  57833. case "ConeEmitter":
  57834. emitterType = new BABYLON.ConeParticleEmitter();
  57835. break;
  57836. case "BoxEmitter":
  57837. default:
  57838. emitterType = new BABYLON.BoxParticleEmitter();
  57839. break;
  57840. }
  57841. emitterType.parse(parsedParticleSystem.particleEmitterType);
  57842. particleSystem.particleEmitterType = emitterType;
  57843. }
  57844. return particleSystem;
  57845. };
  57846. return GPUParticleSystem;
  57847. }());
  57848. BABYLON.GPUParticleSystem = GPUParticleSystem;
  57849. })(BABYLON || (BABYLON = {}));
  57850. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  57851. var BABYLON;
  57852. (function (BABYLON) {
  57853. /**
  57854. * Represents one particle of a solid particle system.
  57855. */
  57856. var SolidParticle = /** @class */ (function () {
  57857. /**
  57858. * Creates a Solid Particle object.
  57859. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  57860. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  57861. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  57862. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  57863. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  57864. * @param shapeId (integer) is the model shape identifier in the SPS.
  57865. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  57866. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  57867. */
  57868. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  57869. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  57870. /**
  57871. * particle global index
  57872. */
  57873. this.idx = 0;
  57874. /**
  57875. * The color of the particle
  57876. */
  57877. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57878. /**
  57879. * The world space position of the particle.
  57880. */
  57881. this.position = BABYLON.Vector3.Zero();
  57882. /**
  57883. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  57884. */
  57885. this.rotation = BABYLON.Vector3.Zero();
  57886. /**
  57887. * The scaling of the particle.
  57888. */
  57889. this.scaling = BABYLON.Vector3.One();
  57890. /**
  57891. * The uvs of the particle.
  57892. */
  57893. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  57894. /**
  57895. * The current speed of the particle.
  57896. */
  57897. this.velocity = BABYLON.Vector3.Zero();
  57898. /**
  57899. * The pivot point in the particle local space.
  57900. */
  57901. this.pivot = BABYLON.Vector3.Zero();
  57902. /**
  57903. * Must the particle be translated from its pivot point in its local space ?
  57904. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  57905. * Default : false
  57906. */
  57907. this.translateFromPivot = false;
  57908. /**
  57909. * Is the particle active or not ?
  57910. */
  57911. this.alive = true;
  57912. /**
  57913. * Is the particle visible or not ?
  57914. */
  57915. this.isVisible = true;
  57916. /**
  57917. * Index of this particle in the global "positions" array (Internal use)
  57918. */
  57919. this._pos = 0;
  57920. /**
  57921. * Index of this particle in the global "indices" array (Internal use)
  57922. */
  57923. this._ind = 0;
  57924. /**
  57925. * ModelShape id of this particle
  57926. */
  57927. this.shapeId = 0;
  57928. /**
  57929. * Index of the particle in its shape id (Internal use)
  57930. */
  57931. this.idxInShape = 0;
  57932. /**
  57933. * Still set as invisible in order to skip useless computations (Internal use)
  57934. */
  57935. this._stillInvisible = false;
  57936. /**
  57937. * Last computed particle rotation matrix
  57938. */
  57939. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  57940. /**
  57941. * Parent particle Id, if any.
  57942. * Default null.
  57943. */
  57944. this.parentId = null;
  57945. /**
  57946. * Internal global position in the SPS.
  57947. */
  57948. this._globalPosition = BABYLON.Vector3.Zero();
  57949. this.idx = particleIndex;
  57950. this._pos = positionIndex;
  57951. this._ind = indiceIndex;
  57952. this._model = model;
  57953. this.shapeId = shapeId;
  57954. this.idxInShape = idxInShape;
  57955. this._sps = sps;
  57956. if (modelBoundingInfo) {
  57957. this._modelBoundingInfo = modelBoundingInfo;
  57958. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  57959. }
  57960. }
  57961. Object.defineProperty(SolidParticle.prototype, "scale", {
  57962. /**
  57963. * Legacy support, changed scale to scaling
  57964. */
  57965. get: function () {
  57966. return this.scaling;
  57967. },
  57968. /**
  57969. * Legacy support, changed scale to scaling
  57970. */
  57971. set: function (scale) {
  57972. this.scaling = scale;
  57973. },
  57974. enumerable: true,
  57975. configurable: true
  57976. });
  57977. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  57978. /**
  57979. * Legacy support, changed quaternion to rotationQuaternion
  57980. */
  57981. get: function () {
  57982. return this.rotationQuaternion;
  57983. },
  57984. /**
  57985. * Legacy support, changed quaternion to rotationQuaternion
  57986. */
  57987. set: function (q) {
  57988. this.rotationQuaternion = q;
  57989. },
  57990. enumerable: true,
  57991. configurable: true
  57992. });
  57993. /**
  57994. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  57995. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  57996. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  57997. * @returns true if it intersects
  57998. */
  57999. SolidParticle.prototype.intersectsMesh = function (target) {
  58000. if (!this._boundingInfo || !target._boundingInfo) {
  58001. return false;
  58002. }
  58003. if (this._sps._bSphereOnly) {
  58004. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  58005. }
  58006. return this._boundingInfo.intersects(target._boundingInfo, false);
  58007. };
  58008. return SolidParticle;
  58009. }());
  58010. BABYLON.SolidParticle = SolidParticle;
  58011. /**
  58012. * Represents the shape of the model used by one particle of a solid particle system.
  58013. * SPS internal tool, don't use it manually.
  58014. */
  58015. var ModelShape = /** @class */ (function () {
  58016. /**
  58017. * 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.
  58018. * SPS internal tool, don't use it manually.
  58019. * @hidden
  58020. */
  58021. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  58022. /**
  58023. * length of the shape in the model indices array (internal use)
  58024. */
  58025. this._indicesLength = 0;
  58026. this.shapeID = id;
  58027. this._shape = shape;
  58028. this._indicesLength = indicesLength;
  58029. this._shapeUV = shapeUV;
  58030. this._positionFunction = posFunction;
  58031. this._vertexFunction = vtxFunction;
  58032. }
  58033. return ModelShape;
  58034. }());
  58035. BABYLON.ModelShape = ModelShape;
  58036. /**
  58037. * Represents a Depth Sorted Particle in the solid particle system.
  58038. */
  58039. var DepthSortedParticle = /** @class */ (function () {
  58040. function DepthSortedParticle() {
  58041. /**
  58042. * Index of the particle in the "indices" array
  58043. */
  58044. this.ind = 0;
  58045. /**
  58046. * Length of the particle shape in the "indices" array
  58047. */
  58048. this.indicesLength = 0;
  58049. /**
  58050. * Squared distance from the particle to the camera
  58051. */
  58052. this.sqDistance = 0.0;
  58053. }
  58054. return DepthSortedParticle;
  58055. }());
  58056. BABYLON.DepthSortedParticle = DepthSortedParticle;
  58057. })(BABYLON || (BABYLON = {}));
  58058. //# sourceMappingURL=babylon.solidParticle.js.map
  58059. var BABYLON;
  58060. (function (BABYLON) {
  58061. /**
  58062. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  58063. *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.
  58064. * The SPS is also a particle system. It provides some methods to manage the particles.
  58065. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  58066. *
  58067. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  58068. */
  58069. var SolidParticleSystem = /** @class */ (function () {
  58070. /**
  58071. * Creates a SPS (Solid Particle System) object.
  58072. * @param name (String) is the SPS name, this will be the underlying mesh name.
  58073. * @param scene (Scene) is the scene in which the SPS is added.
  58074. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  58075. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  58076. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  58077. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  58078. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  58079. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  58080. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  58081. */
  58082. function SolidParticleSystem(name, scene, options) {
  58083. /**
  58084. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  58085. * Example : var p = SPS.particles[i];
  58086. */
  58087. this.particles = new Array();
  58088. /**
  58089. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  58090. */
  58091. this.nbParticles = 0;
  58092. /**
  58093. * If the particles must ever face the camera (default false). Useful for planar particles.
  58094. */
  58095. this.billboard = false;
  58096. /**
  58097. * Recompute normals when adding a shape
  58098. */
  58099. this.recomputeNormals = true;
  58100. /**
  58101. * This a counter ofr your own usage. It's not set by any SPS functions.
  58102. */
  58103. this.counter = 0;
  58104. /**
  58105. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  58106. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  58107. */
  58108. this.vars = {};
  58109. /**
  58110. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  58111. */
  58112. this._bSphereOnly = false;
  58113. /**
  58114. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  58115. */
  58116. this._bSphereRadiusFactor = 1.0;
  58117. this._positions = new Array();
  58118. this._indices = new Array();
  58119. this._normals = new Array();
  58120. this._colors = new Array();
  58121. this._uvs = new Array();
  58122. this._index = 0; // indices index
  58123. this._updatable = true;
  58124. this._pickable = false;
  58125. this._isVisibilityBoxLocked = false;
  58126. this._alwaysVisible = false;
  58127. this._depthSort = false;
  58128. this._shapeCounter = 0;
  58129. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  58130. this._color = new BABYLON.Color4(0, 0, 0, 0);
  58131. this._computeParticleColor = true;
  58132. this._computeParticleTexture = true;
  58133. this._computeParticleRotation = true;
  58134. this._computeParticleVertex = false;
  58135. this._computeBoundingBox = false;
  58136. this._depthSortParticles = true;
  58137. this._cam_axisZ = BABYLON.Vector3.Zero();
  58138. this._cam_axisY = BABYLON.Vector3.Zero();
  58139. this._cam_axisX = BABYLON.Vector3.Zero();
  58140. this._axisZ = BABYLON.Axis.Z;
  58141. this._camDir = BABYLON.Vector3.Zero();
  58142. this._camInvertedPosition = BABYLON.Vector3.Zero();
  58143. this._rotMatrix = new BABYLON.Matrix();
  58144. this._invertMatrix = new BABYLON.Matrix();
  58145. this._rotated = BABYLON.Vector3.Zero();
  58146. this._quaternion = new BABYLON.Quaternion();
  58147. this._vertex = BABYLON.Vector3.Zero();
  58148. this._normal = BABYLON.Vector3.Zero();
  58149. this._yaw = 0.0;
  58150. this._pitch = 0.0;
  58151. this._roll = 0.0;
  58152. this._halfroll = 0.0;
  58153. this._halfpitch = 0.0;
  58154. this._halfyaw = 0.0;
  58155. this._sinRoll = 0.0;
  58156. this._cosRoll = 0.0;
  58157. this._sinPitch = 0.0;
  58158. this._cosPitch = 0.0;
  58159. this._sinYaw = 0.0;
  58160. this._cosYaw = 0.0;
  58161. this._mustUnrotateFixedNormals = false;
  58162. this._minimum = BABYLON.Vector3.Zero();
  58163. this._maximum = BABYLON.Vector3.Zero();
  58164. this._minBbox = BABYLON.Vector3.Zero();
  58165. this._maxBbox = BABYLON.Vector3.Zero();
  58166. this._particlesIntersect = false;
  58167. this._depthSortFunction = function (p1, p2) {
  58168. return (p2.sqDistance - p1.sqDistance);
  58169. };
  58170. this._needs32Bits = false;
  58171. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  58172. this._scaledPivot = BABYLON.Vector3.Zero();
  58173. this._particleHasParent = false;
  58174. this.name = name;
  58175. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  58176. this._camera = scene.activeCamera;
  58177. this._pickable = options ? options.isPickable : false;
  58178. this._depthSort = options ? options.enableDepthSort : false;
  58179. this._particlesIntersect = options ? options.particleIntersection : false;
  58180. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  58181. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  58182. if (options && options.updatable) {
  58183. this._updatable = options.updatable;
  58184. }
  58185. else {
  58186. this._updatable = true;
  58187. }
  58188. if (this._pickable) {
  58189. this.pickedParticles = [];
  58190. }
  58191. if (this._depthSort) {
  58192. this.depthSortedParticles = [];
  58193. }
  58194. }
  58195. /**
  58196. * Builds the SPS underlying mesh. Returns a standard Mesh.
  58197. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  58198. * @returns the created mesh
  58199. */
  58200. SolidParticleSystem.prototype.buildMesh = function () {
  58201. if (this.nbParticles === 0) {
  58202. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  58203. this.addShape(triangle, 1);
  58204. triangle.dispose();
  58205. }
  58206. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  58207. this._positions32 = new Float32Array(this._positions);
  58208. this._uvs32 = new Float32Array(this._uvs);
  58209. this._colors32 = new Float32Array(this._colors);
  58210. if (this.recomputeNormals) {
  58211. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  58212. }
  58213. this._normals32 = new Float32Array(this._normals);
  58214. this._fixedNormal32 = new Float32Array(this._normals);
  58215. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  58216. this._unrotateFixedNormals();
  58217. }
  58218. var vertexData = new BABYLON.VertexData();
  58219. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  58220. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  58221. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  58222. if (this._uvs32.length > 0) {
  58223. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  58224. }
  58225. if (this._colors32.length > 0) {
  58226. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  58227. }
  58228. var mesh = new BABYLON.Mesh(this.name, this._scene);
  58229. vertexData.applyToMesh(mesh, this._updatable);
  58230. this.mesh = mesh;
  58231. this.mesh.isPickable = this._pickable;
  58232. // free memory
  58233. if (!this._depthSort) {
  58234. this._indices = null;
  58235. }
  58236. this._positions = null;
  58237. this._normals = null;
  58238. this._uvs = null;
  58239. this._colors = null;
  58240. if (!this._updatable) {
  58241. this.particles.length = 0;
  58242. }
  58243. return mesh;
  58244. };
  58245. /**
  58246. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  58247. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  58248. * Thus the particles generated from `digest()` have their property `position` set yet.
  58249. * @param mesh ( Mesh ) is the mesh to be digested
  58250. * @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
  58251. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  58252. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  58253. * @returns the current SPS
  58254. */
  58255. SolidParticleSystem.prototype.digest = function (mesh, options) {
  58256. var size = (options && options.facetNb) || 1;
  58257. var number = (options && options.number) || 0;
  58258. var delta = (options && options.delta) || 0;
  58259. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58260. var meshInd = mesh.getIndices();
  58261. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58262. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58263. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58264. var f = 0; // facet counter
  58265. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  58266. // compute size from number
  58267. if (number) {
  58268. number = (number > totalFacets) ? totalFacets : number;
  58269. size = Math.round(totalFacets / number);
  58270. delta = 0;
  58271. }
  58272. else {
  58273. size = (size > totalFacets) ? totalFacets : size;
  58274. }
  58275. var facetPos = []; // submesh positions
  58276. var facetInd = []; // submesh indices
  58277. var facetUV = []; // submesh UV
  58278. var facetCol = []; // submesh colors
  58279. var barycenter = BABYLON.Vector3.Zero();
  58280. var sizeO = size;
  58281. while (f < totalFacets) {
  58282. size = sizeO + Math.floor((1 + delta) * Math.random());
  58283. if (f > totalFacets - size) {
  58284. size = totalFacets - f;
  58285. }
  58286. // reset temp arrays
  58287. facetPos.length = 0;
  58288. facetInd.length = 0;
  58289. facetUV.length = 0;
  58290. facetCol.length = 0;
  58291. // iterate over "size" facets
  58292. var fi = 0;
  58293. for (var j = f * 3; j < (f + size) * 3; j++) {
  58294. facetInd.push(fi);
  58295. var i = meshInd[j];
  58296. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  58297. if (meshUV) {
  58298. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  58299. }
  58300. if (meshCol) {
  58301. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  58302. }
  58303. fi++;
  58304. }
  58305. // create a model shape for each single particle
  58306. var idx = this.nbParticles;
  58307. var shape = this._posToShape(facetPos);
  58308. var shapeUV = this._uvsToShapeUV(facetUV);
  58309. // compute the barycenter of the shape
  58310. var v;
  58311. for (v = 0; v < shape.length; v++) {
  58312. barycenter.addInPlace(shape[v]);
  58313. }
  58314. barycenter.scaleInPlace(1 / shape.length);
  58315. // shift the shape from its barycenter to the origin
  58316. for (v = 0; v < shape.length; v++) {
  58317. shape[v].subtractInPlace(barycenter);
  58318. }
  58319. var bInfo;
  58320. if (this._particlesIntersect) {
  58321. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  58322. }
  58323. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  58324. // add the particle in the SPS
  58325. var currentPos = this._positions.length;
  58326. var currentInd = this._indices.length;
  58327. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  58328. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  58329. // initialize the particle position
  58330. this.particles[this.nbParticles].position.addInPlace(barycenter);
  58331. this._index += shape.length;
  58332. idx++;
  58333. this.nbParticles++;
  58334. this._shapeCounter++;
  58335. f += size;
  58336. }
  58337. return this;
  58338. };
  58339. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  58340. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  58341. var index = 0;
  58342. var idx = 0;
  58343. for (var p = 0; p < this.particles.length; p++) {
  58344. this._particle = this.particles[p];
  58345. this._shape = this._particle._model._shape;
  58346. if (this._particle.rotationQuaternion) {
  58347. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58348. }
  58349. else {
  58350. this._yaw = this._particle.rotation.y;
  58351. this._pitch = this._particle.rotation.x;
  58352. this._roll = this._particle.rotation.z;
  58353. this._quaternionRotationYPR();
  58354. }
  58355. this._quaternionToRotationMatrix();
  58356. this._rotMatrix.invertToRef(this._invertMatrix);
  58357. for (var pt = 0; pt < this._shape.length; pt++) {
  58358. idx = index + pt * 3;
  58359. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  58360. this._fixedNormal32[idx] = this._normal.x;
  58361. this._fixedNormal32[idx + 1] = this._normal.y;
  58362. this._fixedNormal32[idx + 2] = this._normal.z;
  58363. }
  58364. index = idx + 3;
  58365. }
  58366. };
  58367. //reset copy
  58368. SolidParticleSystem.prototype._resetCopy = function () {
  58369. this._copy.position.x = 0;
  58370. this._copy.position.y = 0;
  58371. this._copy.position.z = 0;
  58372. this._copy.rotation.x = 0;
  58373. this._copy.rotation.y = 0;
  58374. this._copy.rotation.z = 0;
  58375. this._copy.rotationQuaternion = null;
  58376. this._copy.scaling.x = 1.0;
  58377. this._copy.scaling.y = 1.0;
  58378. this._copy.scaling.z = 1.0;
  58379. this._copy.uvs.x = 0;
  58380. this._copy.uvs.y = 0;
  58381. this._copy.uvs.z = 1.0;
  58382. this._copy.uvs.w = 1.0;
  58383. this._copy.color = null;
  58384. this._copy.translateFromPivot = false;
  58385. };
  58386. // _meshBuilder : inserts the shape model in the global SPS mesh
  58387. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  58388. var i;
  58389. var u = 0;
  58390. var c = 0;
  58391. var n = 0;
  58392. this._resetCopy();
  58393. if (options && options.positionFunction) { // call to custom positionFunction
  58394. options.positionFunction(this._copy, idx, idxInShape);
  58395. this._mustUnrotateFixedNormals = true;
  58396. }
  58397. if (this._copy.rotationQuaternion) {
  58398. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58399. }
  58400. else {
  58401. this._yaw = this._copy.rotation.y;
  58402. this._pitch = this._copy.rotation.x;
  58403. this._roll = this._copy.rotation.z;
  58404. this._quaternionRotationYPR();
  58405. }
  58406. this._quaternionToRotationMatrix();
  58407. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  58408. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  58409. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  58410. if (this._copy.translateFromPivot) {
  58411. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58412. }
  58413. else {
  58414. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58415. }
  58416. for (i = 0; i < shape.length; i++) {
  58417. this._vertex.x = shape[i].x;
  58418. this._vertex.y = shape[i].y;
  58419. this._vertex.z = shape[i].z;
  58420. if (options && options.vertexFunction) {
  58421. options.vertexFunction(this._copy, this._vertex, i);
  58422. }
  58423. this._vertex.x *= this._copy.scaling.x;
  58424. this._vertex.y *= this._copy.scaling.y;
  58425. this._vertex.z *= this._copy.scaling.z;
  58426. this._vertex.x -= this._scaledPivot.x;
  58427. this._vertex.y -= this._scaledPivot.y;
  58428. this._vertex.z -= this._scaledPivot.z;
  58429. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58430. this._rotated.addInPlace(this._pivotBackTranslation);
  58431. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  58432. if (meshUV) {
  58433. 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);
  58434. u += 2;
  58435. }
  58436. if (this._copy.color) {
  58437. this._color = this._copy.color;
  58438. }
  58439. else if (meshCol && meshCol[c] !== undefined) {
  58440. this._color.r = meshCol[c];
  58441. this._color.g = meshCol[c + 1];
  58442. this._color.b = meshCol[c + 2];
  58443. this._color.a = meshCol[c + 3];
  58444. }
  58445. else {
  58446. this._color.r = 1.0;
  58447. this._color.g = 1.0;
  58448. this._color.b = 1.0;
  58449. this._color.a = 1.0;
  58450. }
  58451. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  58452. c += 4;
  58453. if (!this.recomputeNormals && meshNor) {
  58454. this._normal.x = meshNor[n];
  58455. this._normal.y = meshNor[n + 1];
  58456. this._normal.z = meshNor[n + 2];
  58457. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  58458. normals.push(this._normal.x, this._normal.y, this._normal.z);
  58459. n += 3;
  58460. }
  58461. }
  58462. for (i = 0; i < meshInd.length; i++) {
  58463. var current_ind = p + meshInd[i];
  58464. indices.push(current_ind);
  58465. if (current_ind > 65535) {
  58466. this._needs32Bits = true;
  58467. }
  58468. }
  58469. if (this._pickable) {
  58470. var nbfaces = meshInd.length / 3;
  58471. for (i = 0; i < nbfaces; i++) {
  58472. this.pickedParticles.push({ idx: idx, faceId: i });
  58473. }
  58474. }
  58475. if (this._depthSort) {
  58476. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  58477. }
  58478. return this._copy;
  58479. };
  58480. // returns a shape array from positions array
  58481. SolidParticleSystem.prototype._posToShape = function (positions) {
  58482. var shape = [];
  58483. for (var i = 0; i < positions.length; i += 3) {
  58484. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  58485. }
  58486. return shape;
  58487. };
  58488. // returns a shapeUV array from a Vector4 uvs
  58489. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  58490. var shapeUV = [];
  58491. if (uvs) {
  58492. for (var i = 0; i < uvs.length; i++)
  58493. shapeUV.push(uvs[i]);
  58494. }
  58495. return shapeUV;
  58496. };
  58497. // adds a new particle object in the particles array
  58498. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  58499. if (bInfo === void 0) { bInfo = null; }
  58500. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  58501. this.particles.push(sp);
  58502. return sp;
  58503. };
  58504. /**
  58505. * Adds some particles to the SPS from the model shape. Returns the shape id.
  58506. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  58507. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  58508. * @param nb (positive integer) the number of particles to be created from this model
  58509. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  58510. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  58511. * @returns the number of shapes in the system
  58512. */
  58513. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  58514. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58515. var meshInd = mesh.getIndices();
  58516. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58517. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58518. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58519. var bbInfo;
  58520. if (this._particlesIntersect) {
  58521. bbInfo = mesh.getBoundingInfo();
  58522. }
  58523. var shape = this._posToShape(meshPos);
  58524. var shapeUV = this._uvsToShapeUV(meshUV);
  58525. var posfunc = options ? options.positionFunction : null;
  58526. var vtxfunc = options ? options.vertexFunction : null;
  58527. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  58528. // particles
  58529. var sp;
  58530. var currentCopy;
  58531. var idx = this.nbParticles;
  58532. for (var i = 0; i < nb; i++) {
  58533. var currentPos = this._positions.length;
  58534. var currentInd = this._indices.length;
  58535. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  58536. if (this._updatable) {
  58537. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  58538. sp.position.copyFrom(currentCopy.position);
  58539. sp.rotation.copyFrom(currentCopy.rotation);
  58540. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  58541. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  58542. }
  58543. if (currentCopy.color && sp.color) {
  58544. sp.color.copyFrom(currentCopy.color);
  58545. }
  58546. sp.scaling.copyFrom(currentCopy.scaling);
  58547. sp.uvs.copyFrom(currentCopy.uvs);
  58548. }
  58549. this._index += shape.length;
  58550. idx++;
  58551. }
  58552. this.nbParticles += nb;
  58553. this._shapeCounter++;
  58554. return this._shapeCounter - 1;
  58555. };
  58556. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  58557. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  58558. this._resetCopy();
  58559. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  58560. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  58561. }
  58562. if (this._copy.rotationQuaternion) {
  58563. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58564. }
  58565. else {
  58566. this._yaw = this._copy.rotation.y;
  58567. this._pitch = this._copy.rotation.x;
  58568. this._roll = this._copy.rotation.z;
  58569. this._quaternionRotationYPR();
  58570. }
  58571. this._quaternionToRotationMatrix();
  58572. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  58573. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  58574. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  58575. if (this._copy.translateFromPivot) {
  58576. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58577. }
  58578. else {
  58579. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58580. }
  58581. this._shape = particle._model._shape;
  58582. for (var pt = 0; pt < this._shape.length; pt++) {
  58583. this._vertex.x = this._shape[pt].x;
  58584. this._vertex.y = this._shape[pt].y;
  58585. this._vertex.z = this._shape[pt].z;
  58586. if (particle._model._vertexFunction) {
  58587. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  58588. }
  58589. this._vertex.x *= this._copy.scaling.x;
  58590. this._vertex.y *= this._copy.scaling.y;
  58591. this._vertex.z *= this._copy.scaling.z;
  58592. this._vertex.x -= this._scaledPivot.x;
  58593. this._vertex.y -= this._scaledPivot.y;
  58594. this._vertex.z -= this._scaledPivot.z;
  58595. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58596. this._rotated.addInPlace(this._pivotBackTranslation);
  58597. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  58598. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  58599. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  58600. }
  58601. particle.position.x = 0.0;
  58602. particle.position.y = 0.0;
  58603. particle.position.z = 0.0;
  58604. particle.rotation.x = 0.0;
  58605. particle.rotation.y = 0.0;
  58606. particle.rotation.z = 0.0;
  58607. particle.rotationQuaternion = null;
  58608. particle.scaling.x = 1.0;
  58609. particle.scaling.y = 1.0;
  58610. particle.scaling.z = 1.0;
  58611. particle.uvs.x = 0.0;
  58612. particle.uvs.y = 0.0;
  58613. particle.uvs.z = 1.0;
  58614. particle.uvs.w = 1.0;
  58615. particle.pivot.x = 0.0;
  58616. particle.pivot.y = 0.0;
  58617. particle.pivot.z = 0.0;
  58618. particle.translateFromPivot = false;
  58619. particle.parentId = null;
  58620. };
  58621. /**
  58622. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  58623. * @returns the SPS.
  58624. */
  58625. SolidParticleSystem.prototype.rebuildMesh = function () {
  58626. for (var p = 0; p < this.particles.length; p++) {
  58627. this._rebuildParticle(this.particles[p]);
  58628. }
  58629. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  58630. return this;
  58631. };
  58632. /**
  58633. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  58634. * This method calls `updateParticle()` for each particle of the SPS.
  58635. * For an animated SPS, it is usually called within the render loop.
  58636. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  58637. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  58638. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  58639. * @returns the SPS.
  58640. */
  58641. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  58642. if (start === void 0) { start = 0; }
  58643. if (end === void 0) { end = this.nbParticles - 1; }
  58644. if (update === void 0) { update = true; }
  58645. if (!this._updatable) {
  58646. return this;
  58647. }
  58648. // custom beforeUpdate
  58649. this.beforeUpdateParticles(start, end, update);
  58650. this._cam_axisX.x = 1.0;
  58651. this._cam_axisX.y = 0.0;
  58652. this._cam_axisX.z = 0.0;
  58653. this._cam_axisY.x = 0.0;
  58654. this._cam_axisY.y = 1.0;
  58655. this._cam_axisY.z = 0.0;
  58656. this._cam_axisZ.x = 0.0;
  58657. this._cam_axisZ.y = 0.0;
  58658. this._cam_axisZ.z = 1.0;
  58659. // cases when the World Matrix is to be computed first
  58660. if (this.billboard || this._depthSort) {
  58661. this.mesh.computeWorldMatrix(true);
  58662. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  58663. }
  58664. // if the particles will always face the camera
  58665. if (this.billboard) {
  58666. // compute the camera position and un-rotate it by the current mesh rotation
  58667. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  58668. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  58669. this._cam_axisZ.normalize();
  58670. // same for camera up vector extracted from the cam view matrix
  58671. var view = this._camera.getViewMatrix(true);
  58672. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  58673. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  58674. this._cam_axisY.normalize();
  58675. this._cam_axisX.normalize();
  58676. }
  58677. // if depthSort, compute the camera global position in the mesh local system
  58678. if (this._depthSort) {
  58679. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  58680. }
  58681. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  58682. var idx = 0; // current position index in the global array positions32
  58683. var index = 0; // position start index in the global array positions32 of the current particle
  58684. var colidx = 0; // current color index in the global array colors32
  58685. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  58686. var uvidx = 0; // current uv index in the global array uvs32
  58687. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  58688. var pt = 0; // current index in the particle model shape
  58689. if (this.mesh.isFacetDataEnabled) {
  58690. this._computeBoundingBox = true;
  58691. }
  58692. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  58693. if (this._computeBoundingBox) {
  58694. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  58695. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  58696. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  58697. }
  58698. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  58699. if (this.mesh._boundingInfo) {
  58700. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  58701. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  58702. }
  58703. }
  58704. }
  58705. // particle loop
  58706. index = this.particles[start]._pos;
  58707. var vpos = (index / 3) | 0;
  58708. colorIndex = vpos * 4;
  58709. uvIndex = vpos * 2;
  58710. for (var p = start; p <= end; p++) {
  58711. this._particle = this.particles[p];
  58712. this._shape = this._particle._model._shape;
  58713. this._shapeUV = this._particle._model._shapeUV;
  58714. // call to custom user function to update the particle properties
  58715. this.updateParticle(this._particle);
  58716. // camera-particle distance for depth sorting
  58717. if (this._depthSort && this._depthSortParticles) {
  58718. var dsp = this.depthSortedParticles[p];
  58719. dsp.ind = this._particle._ind;
  58720. dsp.indicesLength = this._particle._model._indicesLength;
  58721. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  58722. }
  58723. // skip the computations for inactive or already invisible particles
  58724. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  58725. // increment indexes for the next particle
  58726. pt = this._shape.length;
  58727. index += pt * 3;
  58728. colorIndex += pt * 4;
  58729. uvIndex += pt * 2;
  58730. continue;
  58731. }
  58732. if (this._particle.isVisible) {
  58733. this._particle._stillInvisible = false; // un-mark permanent invisibility
  58734. this._particleHasParent = (this._particle.parentId !== null);
  58735. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  58736. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  58737. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  58738. // particle rotation matrix
  58739. if (this.billboard) {
  58740. this._particle.rotation.x = 0.0;
  58741. this._particle.rotation.y = 0.0;
  58742. }
  58743. if (this._computeParticleRotation || this.billboard) {
  58744. if (this._particle.rotationQuaternion) {
  58745. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58746. }
  58747. else {
  58748. this._yaw = this._particle.rotation.y;
  58749. this._pitch = this._particle.rotation.x;
  58750. this._roll = this._particle.rotation.z;
  58751. this._quaternionRotationYPR();
  58752. }
  58753. this._quaternionToRotationMatrix();
  58754. }
  58755. if (this._particleHasParent) {
  58756. this._parent = this.particles[this._particle.parentId];
  58757. 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];
  58758. 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];
  58759. 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];
  58760. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  58761. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  58762. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  58763. if (this._computeParticleRotation || this.billboard) {
  58764. 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];
  58765. 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];
  58766. 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];
  58767. 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];
  58768. 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];
  58769. 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];
  58770. 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];
  58771. 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];
  58772. 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];
  58773. }
  58774. }
  58775. else {
  58776. this._particle._globalPosition.x = this._particle.position.x;
  58777. this._particle._globalPosition.y = this._particle.position.y;
  58778. this._particle._globalPosition.z = this._particle.position.z;
  58779. if (this._computeParticleRotation || this.billboard) {
  58780. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  58781. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  58782. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  58783. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  58784. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  58785. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  58786. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  58787. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  58788. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  58789. }
  58790. }
  58791. if (this._particle.translateFromPivot) {
  58792. this._pivotBackTranslation.x = 0.0;
  58793. this._pivotBackTranslation.y = 0.0;
  58794. this._pivotBackTranslation.z = 0.0;
  58795. }
  58796. else {
  58797. this._pivotBackTranslation.x = this._scaledPivot.x;
  58798. this._pivotBackTranslation.y = this._scaledPivot.y;
  58799. this._pivotBackTranslation.z = this._scaledPivot.z;
  58800. }
  58801. // particle vertex loop
  58802. for (pt = 0; pt < this._shape.length; pt++) {
  58803. idx = index + pt * 3;
  58804. colidx = colorIndex + pt * 4;
  58805. uvidx = uvIndex + pt * 2;
  58806. this._vertex.x = this._shape[pt].x;
  58807. this._vertex.y = this._shape[pt].y;
  58808. this._vertex.z = this._shape[pt].z;
  58809. if (this._computeParticleVertex) {
  58810. this.updateParticleVertex(this._particle, this._vertex, pt);
  58811. }
  58812. // positions
  58813. this._vertex.x *= this._particle.scaling.x;
  58814. this._vertex.y *= this._particle.scaling.y;
  58815. this._vertex.z *= this._particle.scaling.z;
  58816. this._vertex.x -= this._scaledPivot.x;
  58817. this._vertex.y -= this._scaledPivot.y;
  58818. this._vertex.z -= this._scaledPivot.z;
  58819. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  58820. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  58821. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  58822. this._rotated.x += this._pivotBackTranslation.x;
  58823. this._rotated.y += this._pivotBackTranslation.y;
  58824. this._rotated.z += this._pivotBackTranslation.z;
  58825. 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;
  58826. 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;
  58827. 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;
  58828. if (this._computeBoundingBox) {
  58829. if (this._positions32[idx] < this._minimum.x) {
  58830. this._minimum.x = this._positions32[idx];
  58831. }
  58832. if (this._positions32[idx] > this._maximum.x) {
  58833. this._maximum.x = this._positions32[idx];
  58834. }
  58835. if (this._positions32[idx + 1] < this._minimum.y) {
  58836. this._minimum.y = this._positions32[idx + 1];
  58837. }
  58838. if (this._positions32[idx + 1] > this._maximum.y) {
  58839. this._maximum.y = this._positions32[idx + 1];
  58840. }
  58841. if (this._positions32[idx + 2] < this._minimum.z) {
  58842. this._minimum.z = this._positions32[idx + 2];
  58843. }
  58844. if (this._positions32[idx + 2] > this._maximum.z) {
  58845. this._maximum.z = this._positions32[idx + 2];
  58846. }
  58847. }
  58848. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  58849. if (!this._computeParticleVertex) {
  58850. this._normal.x = this._fixedNormal32[idx];
  58851. this._normal.y = this._fixedNormal32[idx + 1];
  58852. this._normal.z = this._fixedNormal32[idx + 2];
  58853. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  58854. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  58855. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  58856. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  58857. 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;
  58858. 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;
  58859. }
  58860. if (this._computeParticleColor && this._particle.color) {
  58861. this._colors32[colidx] = this._particle.color.r;
  58862. this._colors32[colidx + 1] = this._particle.color.g;
  58863. this._colors32[colidx + 2] = this._particle.color.b;
  58864. this._colors32[colidx + 3] = this._particle.color.a;
  58865. }
  58866. if (this._computeParticleTexture) {
  58867. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  58868. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  58869. }
  58870. }
  58871. }
  58872. // particle just set invisible : scaled to zero and positioned at the origin
  58873. else {
  58874. this._particle._stillInvisible = true; // mark the particle as invisible
  58875. for (pt = 0; pt < this._shape.length; pt++) {
  58876. idx = index + pt * 3;
  58877. colidx = colorIndex + pt * 4;
  58878. uvidx = uvIndex + pt * 2;
  58879. this._positions32[idx] = 0.0;
  58880. this._positions32[idx + 1] = 0.0;
  58881. this._positions32[idx + 2] = 0.0;
  58882. this._normals32[idx] = 0.0;
  58883. this._normals32[idx + 1] = 0.0;
  58884. this._normals32[idx + 2] = 0.0;
  58885. if (this._computeParticleColor && this._particle.color) {
  58886. this._colors32[colidx] = this._particle.color.r;
  58887. this._colors32[colidx + 1] = this._particle.color.g;
  58888. this._colors32[colidx + 2] = this._particle.color.b;
  58889. this._colors32[colidx + 3] = this._particle.color.a;
  58890. }
  58891. if (this._computeParticleTexture) {
  58892. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  58893. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  58894. }
  58895. }
  58896. }
  58897. // if the particle intersections must be computed : update the bbInfo
  58898. if (this._particlesIntersect) {
  58899. var bInfo = this._particle._boundingInfo;
  58900. var bBox = bInfo.boundingBox;
  58901. var bSphere = bInfo.boundingSphere;
  58902. if (!this._bSphereOnly) {
  58903. // place, scale and rotate the particle bbox within the SPS local system, then update it
  58904. for (var b = 0; b < bBox.vectors.length; b++) {
  58905. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  58906. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  58907. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  58908. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  58909. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  58910. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  58911. 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;
  58912. 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;
  58913. 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;
  58914. }
  58915. bBox._update(this.mesh._worldMatrix);
  58916. }
  58917. // place and scale the particle bouding sphere in the SPS local system, then update it
  58918. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  58919. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  58920. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  58921. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  58922. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  58923. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  58924. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  58925. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  58926. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  58927. 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));
  58928. bSphere._update(this.mesh._worldMatrix);
  58929. }
  58930. // increment indexes for the next particle
  58931. index = idx + 3;
  58932. colorIndex = colidx + 4;
  58933. uvIndex = uvidx + 2;
  58934. }
  58935. // if the VBO must be updated
  58936. if (update) {
  58937. if (this._computeParticleColor) {
  58938. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  58939. }
  58940. if (this._computeParticleTexture) {
  58941. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  58942. }
  58943. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  58944. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  58945. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  58946. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  58947. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  58948. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  58949. for (var i = 0; i < this._normals32.length; i++) {
  58950. this._fixedNormal32[i] = this._normals32[i];
  58951. }
  58952. }
  58953. if (!this.mesh.areNormalsFrozen) {
  58954. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  58955. }
  58956. }
  58957. if (this._depthSort && this._depthSortParticles) {
  58958. this.depthSortedParticles.sort(this._depthSortFunction);
  58959. var dspl = this.depthSortedParticles.length;
  58960. var sorted = 0;
  58961. var lind = 0;
  58962. var sind = 0;
  58963. var sid = 0;
  58964. for (sorted = 0; sorted < dspl; sorted++) {
  58965. lind = this.depthSortedParticles[sorted].indicesLength;
  58966. sind = this.depthSortedParticles[sorted].ind;
  58967. for (var i = 0; i < lind; i++) {
  58968. this._indices32[sid] = this._indices[sind + i];
  58969. sid++;
  58970. }
  58971. }
  58972. this.mesh.updateIndices(this._indices32);
  58973. }
  58974. }
  58975. if (this._computeBoundingBox) {
  58976. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  58977. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  58978. }
  58979. this.afterUpdateParticles(start, end, update);
  58980. return this;
  58981. };
  58982. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  58983. this._halfroll = this._roll * 0.5;
  58984. this._halfpitch = this._pitch * 0.5;
  58985. this._halfyaw = this._yaw * 0.5;
  58986. this._sinRoll = Math.sin(this._halfroll);
  58987. this._cosRoll = Math.cos(this._halfroll);
  58988. this._sinPitch = Math.sin(this._halfpitch);
  58989. this._cosPitch = Math.cos(this._halfpitch);
  58990. this._sinYaw = Math.sin(this._halfyaw);
  58991. this._cosYaw = Math.cos(this._halfyaw);
  58992. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  58993. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  58994. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  58995. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  58996. };
  58997. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  58998. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  58999. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  59000. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  59001. this._rotMatrix.m[3] = 0;
  59002. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  59003. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  59004. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  59005. this._rotMatrix.m[7] = 0;
  59006. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  59007. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  59008. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  59009. this._rotMatrix.m[11] = 0;
  59010. this._rotMatrix.m[12] = 0;
  59011. this._rotMatrix.m[13] = 0;
  59012. this._rotMatrix.m[14] = 0;
  59013. this._rotMatrix.m[15] = 1.0;
  59014. };
  59015. /**
  59016. * Disposes the SPS.
  59017. */
  59018. SolidParticleSystem.prototype.dispose = function () {
  59019. this.mesh.dispose();
  59020. this.vars = null;
  59021. // drop references to internal big arrays for the GC
  59022. this._positions = null;
  59023. this._indices = null;
  59024. this._normals = null;
  59025. this._uvs = null;
  59026. this._colors = null;
  59027. this._indices32 = null;
  59028. this._positions32 = null;
  59029. this._normals32 = null;
  59030. this._fixedNormal32 = null;
  59031. this._uvs32 = null;
  59032. this._colors32 = null;
  59033. this.pickedParticles = null;
  59034. };
  59035. /**
  59036. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  59037. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59038. * @returns the SPS.
  59039. */
  59040. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  59041. if (!this._isVisibilityBoxLocked) {
  59042. this.mesh.refreshBoundingInfo();
  59043. }
  59044. return this;
  59045. };
  59046. /**
  59047. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  59048. * @param size the size (float) of the visibility box
  59049. * note : this doesn't lock the SPS mesh bounding box.
  59050. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59051. */
  59052. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  59053. var vis = size / 2;
  59054. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  59055. };
  59056. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  59057. /**
  59058. * Gets whether the SPS as always visible or not
  59059. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59060. */
  59061. get: function () {
  59062. return this._alwaysVisible;
  59063. },
  59064. /**
  59065. * Sets the SPS as always visible or not
  59066. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59067. */
  59068. set: function (val) {
  59069. this._alwaysVisible = val;
  59070. this.mesh.alwaysSelectAsActiveMesh = val;
  59071. },
  59072. enumerable: true,
  59073. configurable: true
  59074. });
  59075. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  59076. /**
  59077. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  59078. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59079. */
  59080. get: function () {
  59081. return this._isVisibilityBoxLocked;
  59082. },
  59083. /**
  59084. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  59085. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59086. */
  59087. set: function (val) {
  59088. this._isVisibilityBoxLocked = val;
  59089. var boundingInfo = this.mesh.getBoundingInfo();
  59090. boundingInfo.isLocked = val;
  59091. },
  59092. enumerable: true,
  59093. configurable: true
  59094. });
  59095. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  59096. /**
  59097. * Gets if `setParticles()` computes the particle rotations or not.
  59098. * Default value : true. The SPS is faster when it's set to false.
  59099. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  59100. */
  59101. get: function () {
  59102. return this._computeParticleRotation;
  59103. },
  59104. /**
  59105. * Tells to `setParticles()` to compute the particle rotations or not.
  59106. * Default value : true. The SPS is faster when it's set to false.
  59107. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  59108. */
  59109. set: function (val) {
  59110. this._computeParticleRotation = val;
  59111. },
  59112. enumerable: true,
  59113. configurable: true
  59114. });
  59115. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  59116. /**
  59117. * Gets if `setParticles()` computes the particle colors or not.
  59118. * Default value : true. The SPS is faster when it's set to false.
  59119. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59120. */
  59121. get: function () {
  59122. return this._computeParticleColor;
  59123. },
  59124. /**
  59125. * Tells to `setParticles()` to compute the particle colors or not.
  59126. * Default value : true. The SPS is faster when it's set to false.
  59127. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59128. */
  59129. set: function (val) {
  59130. this._computeParticleColor = val;
  59131. },
  59132. enumerable: true,
  59133. configurable: true
  59134. });
  59135. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  59136. /**
  59137. * Gets if `setParticles()` computes the particle textures or not.
  59138. * Default value : true. The SPS is faster when it's set to false.
  59139. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  59140. */
  59141. get: function () {
  59142. return this._computeParticleTexture;
  59143. },
  59144. set: function (val) {
  59145. this._computeParticleTexture = val;
  59146. },
  59147. enumerable: true,
  59148. configurable: true
  59149. });
  59150. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  59151. /**
  59152. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  59153. * Default value : false. The SPS is faster when it's set to false.
  59154. * Note : the particle custom vertex positions aren't stored values.
  59155. */
  59156. get: function () {
  59157. return this._computeParticleVertex;
  59158. },
  59159. /**
  59160. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  59161. * Default value : false. The SPS is faster when it's set to false.
  59162. * Note : the particle custom vertex positions aren't stored values.
  59163. */
  59164. set: function (val) {
  59165. this._computeParticleVertex = val;
  59166. },
  59167. enumerable: true,
  59168. configurable: true
  59169. });
  59170. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  59171. /**
  59172. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  59173. */
  59174. get: function () {
  59175. return this._computeBoundingBox;
  59176. },
  59177. /**
  59178. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  59179. */
  59180. set: function (val) {
  59181. this._computeBoundingBox = val;
  59182. },
  59183. enumerable: true,
  59184. configurable: true
  59185. });
  59186. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  59187. /**
  59188. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  59189. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59190. * Default : `true`
  59191. */
  59192. get: function () {
  59193. return this._depthSortParticles;
  59194. },
  59195. /**
  59196. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  59197. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59198. * Default : `true`
  59199. */
  59200. set: function (val) {
  59201. this._depthSortParticles = val;
  59202. },
  59203. enumerable: true,
  59204. configurable: true
  59205. });
  59206. // =======================================================================
  59207. // Particle behavior logic
  59208. // these following methods may be overwritten by the user to fit his needs
  59209. /**
  59210. * This function does nothing. It may be overwritten to set all the particle first values.
  59211. * The SPS doesn't call this function, you may have to call it by your own.
  59212. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59213. */
  59214. SolidParticleSystem.prototype.initParticles = function () {
  59215. };
  59216. /**
  59217. * This function does nothing. It may be overwritten to recycle a particle.
  59218. * The SPS doesn't call this function, you may have to call it by your own.
  59219. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59220. * @param particle The particle to recycle
  59221. * @returns the recycled particle
  59222. */
  59223. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  59224. return particle;
  59225. };
  59226. /**
  59227. * Updates a particle : this function should be overwritten by the user.
  59228. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  59229. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59230. * @example : just set a particle position or velocity and recycle conditions
  59231. * @param particle The particle to update
  59232. * @returns the updated particle
  59233. */
  59234. SolidParticleSystem.prototype.updateParticle = function (particle) {
  59235. return particle;
  59236. };
  59237. /**
  59238. * Updates a vertex of a particle : it can be overwritten by the user.
  59239. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  59240. * @param particle the current particle
  59241. * @param vertex the current index of the current particle
  59242. * @param pt the index of the current vertex in the particle shape
  59243. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  59244. * @example : just set a vertex particle position
  59245. * @returns the updated vertex
  59246. */
  59247. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  59248. return vertex;
  59249. };
  59250. /**
  59251. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  59252. * This does nothing and may be overwritten by the user.
  59253. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59254. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59255. * @param update the boolean update value actually passed to setParticles()
  59256. */
  59257. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  59258. };
  59259. /**
  59260. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  59261. * This will be passed three parameters.
  59262. * This does nothing and may be overwritten by the user.
  59263. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59264. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59265. * @param update the boolean update value actually passed to setParticles()
  59266. */
  59267. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  59268. };
  59269. return SolidParticleSystem;
  59270. }());
  59271. BABYLON.SolidParticleSystem = SolidParticleSystem;
  59272. })(BABYLON || (BABYLON = {}));
  59273. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  59274. var BABYLON;
  59275. (function (BABYLON) {
  59276. var ShaderMaterial = /** @class */ (function (_super) {
  59277. __extends(ShaderMaterial, _super);
  59278. function ShaderMaterial(name, scene, shaderPath, options) {
  59279. var _this = _super.call(this, name, scene) || this;
  59280. _this._textures = {};
  59281. _this._textureArrays = {};
  59282. _this._floats = {};
  59283. _this._ints = {};
  59284. _this._floatsArrays = {};
  59285. _this._colors3 = {};
  59286. _this._colors3Arrays = {};
  59287. _this._colors4 = {};
  59288. _this._vectors2 = {};
  59289. _this._vectors3 = {};
  59290. _this._vectors4 = {};
  59291. _this._matrices = {};
  59292. _this._matrices3x3 = {};
  59293. _this._matrices2x2 = {};
  59294. _this._vectors2Arrays = {};
  59295. _this._vectors3Arrays = {};
  59296. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  59297. _this._shaderPath = shaderPath;
  59298. options.needAlphaBlending = options.needAlphaBlending || false;
  59299. options.needAlphaTesting = options.needAlphaTesting || false;
  59300. options.attributes = options.attributes || ["position", "normal", "uv"];
  59301. options.uniforms = options.uniforms || ["worldViewProjection"];
  59302. options.uniformBuffers = options.uniformBuffers || [];
  59303. options.samplers = options.samplers || [];
  59304. options.defines = options.defines || [];
  59305. _this._options = options;
  59306. return _this;
  59307. }
  59308. ShaderMaterial.prototype.getClassName = function () {
  59309. return "ShaderMaterial";
  59310. };
  59311. ShaderMaterial.prototype.needAlphaBlending = function () {
  59312. return this._options.needAlphaBlending;
  59313. };
  59314. ShaderMaterial.prototype.needAlphaTesting = function () {
  59315. return this._options.needAlphaTesting;
  59316. };
  59317. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  59318. if (this._options.uniforms.indexOf(uniformName) === -1) {
  59319. this._options.uniforms.push(uniformName);
  59320. }
  59321. };
  59322. ShaderMaterial.prototype.setTexture = function (name, texture) {
  59323. if (this._options.samplers.indexOf(name) === -1) {
  59324. this._options.samplers.push(name);
  59325. }
  59326. this._textures[name] = texture;
  59327. return this;
  59328. };
  59329. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  59330. if (this._options.samplers.indexOf(name) === -1) {
  59331. this._options.samplers.push(name);
  59332. }
  59333. this._checkUniform(name);
  59334. this._textureArrays[name] = textures;
  59335. return this;
  59336. };
  59337. ShaderMaterial.prototype.setFloat = function (name, value) {
  59338. this._checkUniform(name);
  59339. this._floats[name] = value;
  59340. return this;
  59341. };
  59342. ShaderMaterial.prototype.setInt = function (name, value) {
  59343. this._checkUniform(name);
  59344. this._ints[name] = value;
  59345. return this;
  59346. };
  59347. ShaderMaterial.prototype.setFloats = function (name, value) {
  59348. this._checkUniform(name);
  59349. this._floatsArrays[name] = value;
  59350. return this;
  59351. };
  59352. ShaderMaterial.prototype.setColor3 = function (name, value) {
  59353. this._checkUniform(name);
  59354. this._colors3[name] = value;
  59355. return this;
  59356. };
  59357. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  59358. this._checkUniform(name);
  59359. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  59360. color.toArray(arr, arr.length);
  59361. return arr;
  59362. }, []);
  59363. return this;
  59364. };
  59365. ShaderMaterial.prototype.setColor4 = function (name, value) {
  59366. this._checkUniform(name);
  59367. this._colors4[name] = value;
  59368. return this;
  59369. };
  59370. ShaderMaterial.prototype.setVector2 = function (name, value) {
  59371. this._checkUniform(name);
  59372. this._vectors2[name] = value;
  59373. return this;
  59374. };
  59375. ShaderMaterial.prototype.setVector3 = function (name, value) {
  59376. this._checkUniform(name);
  59377. this._vectors3[name] = value;
  59378. return this;
  59379. };
  59380. ShaderMaterial.prototype.setVector4 = function (name, value) {
  59381. this._checkUniform(name);
  59382. this._vectors4[name] = value;
  59383. return this;
  59384. };
  59385. ShaderMaterial.prototype.setMatrix = function (name, value) {
  59386. this._checkUniform(name);
  59387. this._matrices[name] = value;
  59388. return this;
  59389. };
  59390. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  59391. this._checkUniform(name);
  59392. this._matrices3x3[name] = value;
  59393. return this;
  59394. };
  59395. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  59396. this._checkUniform(name);
  59397. this._matrices2x2[name] = value;
  59398. return this;
  59399. };
  59400. ShaderMaterial.prototype.setArray2 = function (name, value) {
  59401. this._checkUniform(name);
  59402. this._vectors2Arrays[name] = value;
  59403. return this;
  59404. };
  59405. ShaderMaterial.prototype.setArray3 = function (name, value) {
  59406. this._checkUniform(name);
  59407. this._vectors3Arrays[name] = value;
  59408. return this;
  59409. };
  59410. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  59411. if (!mesh) {
  59412. return true;
  59413. }
  59414. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  59415. return false;
  59416. }
  59417. return false;
  59418. };
  59419. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  59420. var scene = this.getScene();
  59421. var engine = scene.getEngine();
  59422. if (!this.checkReadyOnEveryCall) {
  59423. if (this._renderId === scene.getRenderId()) {
  59424. if (this._checkCache(scene, mesh, useInstances)) {
  59425. return true;
  59426. }
  59427. }
  59428. }
  59429. // Instances
  59430. var defines = [];
  59431. var attribs = [];
  59432. var fallbacks = new BABYLON.EffectFallbacks();
  59433. if (useInstances) {
  59434. defines.push("#define INSTANCES");
  59435. }
  59436. for (var index = 0; index < this._options.defines.length; index++) {
  59437. defines.push(this._options.defines[index]);
  59438. }
  59439. for (var index = 0; index < this._options.attributes.length; index++) {
  59440. attribs.push(this._options.attributes[index]);
  59441. }
  59442. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  59443. attribs.push(BABYLON.VertexBuffer.ColorKind);
  59444. defines.push("#define VERTEXCOLOR");
  59445. }
  59446. // Bones
  59447. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59448. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59449. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59450. if (mesh.numBoneInfluencers > 4) {
  59451. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59452. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59453. }
  59454. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59455. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  59456. fallbacks.addCPUSkinningFallback(0, mesh);
  59457. if (this._options.uniforms.indexOf("mBones") === -1) {
  59458. this._options.uniforms.push("mBones");
  59459. }
  59460. }
  59461. else {
  59462. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59463. }
  59464. // Textures
  59465. for (var name in this._textures) {
  59466. if (!this._textures[name].isReady()) {
  59467. return false;
  59468. }
  59469. }
  59470. // Alpha test
  59471. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  59472. defines.push("#define ALPHATEST");
  59473. }
  59474. var previousEffect = this._effect;
  59475. var join = defines.join("\n");
  59476. this._effect = engine.createEffect(this._shaderPath, {
  59477. attributes: attribs,
  59478. uniformsNames: this._options.uniforms,
  59479. uniformBuffersNames: this._options.uniformBuffers,
  59480. samplers: this._options.samplers,
  59481. defines: join,
  59482. fallbacks: fallbacks,
  59483. onCompiled: this.onCompiled,
  59484. onError: this.onError
  59485. }, engine);
  59486. if (!this._effect.isReady()) {
  59487. return false;
  59488. }
  59489. if (previousEffect !== this._effect) {
  59490. scene.resetCachedMaterial();
  59491. }
  59492. this._renderId = scene.getRenderId();
  59493. return true;
  59494. };
  59495. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  59496. var scene = this.getScene();
  59497. if (!this._effect) {
  59498. return;
  59499. }
  59500. if (this._options.uniforms.indexOf("world") !== -1) {
  59501. this._effect.setMatrix("world", world);
  59502. }
  59503. if (this._options.uniforms.indexOf("worldView") !== -1) {
  59504. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  59505. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  59506. }
  59507. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  59508. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  59509. }
  59510. };
  59511. ShaderMaterial.prototype.bind = function (world, mesh) {
  59512. // Std values
  59513. this.bindOnlyWorldMatrix(world);
  59514. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  59515. if (this._options.uniforms.indexOf("view") !== -1) {
  59516. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  59517. }
  59518. if (this._options.uniforms.indexOf("projection") !== -1) {
  59519. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  59520. }
  59521. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  59522. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  59523. }
  59524. // Bones
  59525. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  59526. var name;
  59527. // Texture
  59528. for (name in this._textures) {
  59529. this._effect.setTexture(name, this._textures[name]);
  59530. }
  59531. // Texture arrays
  59532. for (name in this._textureArrays) {
  59533. this._effect.setTextureArray(name, this._textureArrays[name]);
  59534. }
  59535. // Int
  59536. for (name in this._ints) {
  59537. this._effect.setInt(name, this._ints[name]);
  59538. }
  59539. // Float
  59540. for (name in this._floats) {
  59541. this._effect.setFloat(name, this._floats[name]);
  59542. }
  59543. // Floats
  59544. for (name in this._floatsArrays) {
  59545. this._effect.setArray(name, this._floatsArrays[name]);
  59546. }
  59547. // Color3
  59548. for (name in this._colors3) {
  59549. this._effect.setColor3(name, this._colors3[name]);
  59550. }
  59551. for (name in this._colors3Arrays) {
  59552. this._effect.setArray3(name, this._colors3Arrays[name]);
  59553. }
  59554. // Color4
  59555. for (name in this._colors4) {
  59556. var color = this._colors4[name];
  59557. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  59558. }
  59559. // Vector2
  59560. for (name in this._vectors2) {
  59561. this._effect.setVector2(name, this._vectors2[name]);
  59562. }
  59563. // Vector3
  59564. for (name in this._vectors3) {
  59565. this._effect.setVector3(name, this._vectors3[name]);
  59566. }
  59567. // Vector4
  59568. for (name in this._vectors4) {
  59569. this._effect.setVector4(name, this._vectors4[name]);
  59570. }
  59571. // Matrix
  59572. for (name in this._matrices) {
  59573. this._effect.setMatrix(name, this._matrices[name]);
  59574. }
  59575. // Matrix 3x3
  59576. for (name in this._matrices3x3) {
  59577. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  59578. }
  59579. // Matrix 2x2
  59580. for (name in this._matrices2x2) {
  59581. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  59582. }
  59583. // Vector2Array
  59584. for (name in this._vectors2Arrays) {
  59585. this._effect.setArray2(name, this._vectors2Arrays[name]);
  59586. }
  59587. // Vector3Array
  59588. for (name in this._vectors3Arrays) {
  59589. this._effect.setArray3(name, this._vectors3Arrays[name]);
  59590. }
  59591. }
  59592. this._afterBind(mesh);
  59593. };
  59594. ShaderMaterial.prototype.getActiveTextures = function () {
  59595. var activeTextures = _super.prototype.getActiveTextures.call(this);
  59596. for (var name in this._textures) {
  59597. activeTextures.push(this._textures[name]);
  59598. }
  59599. for (var name in this._textureArrays) {
  59600. var array = this._textureArrays[name];
  59601. for (var index = 0; index < array.length; index++) {
  59602. activeTextures.push(array[index]);
  59603. }
  59604. }
  59605. return activeTextures;
  59606. };
  59607. ShaderMaterial.prototype.hasTexture = function (texture) {
  59608. if (_super.prototype.hasTexture.call(this, texture)) {
  59609. return true;
  59610. }
  59611. for (var name in this._textures) {
  59612. if (this._textures[name] === texture) {
  59613. return true;
  59614. }
  59615. }
  59616. for (var name in this._textureArrays) {
  59617. var array = this._textureArrays[name];
  59618. for (var index = 0; index < array.length; index++) {
  59619. if (array[index] === texture) {
  59620. return true;
  59621. }
  59622. }
  59623. }
  59624. return false;
  59625. };
  59626. ShaderMaterial.prototype.clone = function (name) {
  59627. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  59628. return newShaderMaterial;
  59629. };
  59630. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  59631. if (forceDisposeTextures) {
  59632. var name;
  59633. for (name in this._textures) {
  59634. this._textures[name].dispose();
  59635. }
  59636. for (name in this._textureArrays) {
  59637. var array = this._textureArrays[name];
  59638. for (var index = 0; index < array.length; index++) {
  59639. array[index].dispose();
  59640. }
  59641. }
  59642. }
  59643. this._textures = {};
  59644. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  59645. };
  59646. ShaderMaterial.prototype.serialize = function () {
  59647. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  59648. serializationObject.customType = "BABYLON.ShaderMaterial";
  59649. serializationObject.options = this._options;
  59650. serializationObject.shaderPath = this._shaderPath;
  59651. var name;
  59652. // Texture
  59653. serializationObject.textures = {};
  59654. for (name in this._textures) {
  59655. serializationObject.textures[name] = this._textures[name].serialize();
  59656. }
  59657. // Texture arrays
  59658. serializationObject.textureArrays = {};
  59659. for (name in this._textureArrays) {
  59660. serializationObject.textureArrays[name] = [];
  59661. var array = this._textureArrays[name];
  59662. for (var index = 0; index < array.length; index++) {
  59663. serializationObject.textureArrays[name].push(array[index].serialize());
  59664. }
  59665. }
  59666. // Float
  59667. serializationObject.floats = {};
  59668. for (name in this._floats) {
  59669. serializationObject.floats[name] = this._floats[name];
  59670. }
  59671. // Float s
  59672. serializationObject.FloatArrays = {};
  59673. for (name in this._floatsArrays) {
  59674. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  59675. }
  59676. // Color3
  59677. serializationObject.colors3 = {};
  59678. for (name in this._colors3) {
  59679. serializationObject.colors3[name] = this._colors3[name].asArray();
  59680. }
  59681. // Color3 array
  59682. serializationObject.colors3Arrays = {};
  59683. for (name in this._colors3Arrays) {
  59684. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  59685. }
  59686. // Color4
  59687. serializationObject.colors4 = {};
  59688. for (name in this._colors4) {
  59689. serializationObject.colors4[name] = this._colors4[name].asArray();
  59690. }
  59691. // Vector2
  59692. serializationObject.vectors2 = {};
  59693. for (name in this._vectors2) {
  59694. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  59695. }
  59696. // Vector3
  59697. serializationObject.vectors3 = {};
  59698. for (name in this._vectors3) {
  59699. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  59700. }
  59701. // Vector4
  59702. serializationObject.vectors4 = {};
  59703. for (name in this._vectors4) {
  59704. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  59705. }
  59706. // Matrix
  59707. serializationObject.matrices = {};
  59708. for (name in this._matrices) {
  59709. serializationObject.matrices[name] = this._matrices[name].asArray();
  59710. }
  59711. // Matrix 3x3
  59712. serializationObject.matrices3x3 = {};
  59713. for (name in this._matrices3x3) {
  59714. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  59715. }
  59716. // Matrix 2x2
  59717. serializationObject.matrices2x2 = {};
  59718. for (name in this._matrices2x2) {
  59719. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  59720. }
  59721. // Vector2Array
  59722. serializationObject.vectors2Arrays = {};
  59723. for (name in this._vectors2Arrays) {
  59724. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  59725. }
  59726. // Vector3Array
  59727. serializationObject.vectors3Arrays = {};
  59728. for (name in this._vectors3Arrays) {
  59729. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  59730. }
  59731. return serializationObject;
  59732. };
  59733. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  59734. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  59735. var name;
  59736. // Texture
  59737. for (name in source.textures) {
  59738. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  59739. }
  59740. // Texture arrays
  59741. for (name in source.textureArrays) {
  59742. var array = source.textureArrays[name];
  59743. var textureArray = new Array();
  59744. for (var index = 0; index < array.length; index++) {
  59745. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  59746. }
  59747. material.setTextureArray(name, textureArray);
  59748. }
  59749. // Float
  59750. for (name in source.floats) {
  59751. material.setFloat(name, source.floats[name]);
  59752. }
  59753. // Float s
  59754. for (name in source.floatsArrays) {
  59755. material.setFloats(name, source.floatsArrays[name]);
  59756. }
  59757. // Color3
  59758. for (name in source.colors3) {
  59759. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  59760. }
  59761. // Color3 arrays
  59762. for (name in source.colors3Arrays) {
  59763. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  59764. if (i % 3 === 0) {
  59765. arr.push([num]);
  59766. }
  59767. else {
  59768. arr[arr.length - 1].push(num);
  59769. }
  59770. return arr;
  59771. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  59772. material.setColor3Array(name, colors);
  59773. }
  59774. // Color4
  59775. for (name in source.colors4) {
  59776. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  59777. }
  59778. // Vector2
  59779. for (name in source.vectors2) {
  59780. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  59781. }
  59782. // Vector3
  59783. for (name in source.vectors3) {
  59784. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  59785. }
  59786. // Vector4
  59787. for (name in source.vectors4) {
  59788. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  59789. }
  59790. // Matrix
  59791. for (name in source.matrices) {
  59792. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  59793. }
  59794. // Matrix 3x3
  59795. for (name in source.matrices3x3) {
  59796. material.setMatrix3x3(name, source.matrices3x3[name]);
  59797. }
  59798. // Matrix 2x2
  59799. for (name in source.matrices2x2) {
  59800. material.setMatrix2x2(name, source.matrices2x2[name]);
  59801. }
  59802. // Vector2Array
  59803. for (name in source.vectors2Arrays) {
  59804. material.setArray2(name, source.vectors2Arrays[name]);
  59805. }
  59806. // Vector3Array
  59807. for (name in source.vectors3Arrays) {
  59808. material.setArray3(name, source.vectors3Arrays[name]);
  59809. }
  59810. return material;
  59811. };
  59812. return ShaderMaterial;
  59813. }(BABYLON.Material));
  59814. BABYLON.ShaderMaterial = ShaderMaterial;
  59815. })(BABYLON || (BABYLON = {}));
  59816. //# sourceMappingURL=babylon.shaderMaterial.js.map
  59817. var BABYLON;
  59818. (function (BABYLON) {
  59819. var GroundMesh = /** @class */ (function (_super) {
  59820. __extends(GroundMesh, _super);
  59821. function GroundMesh(name, scene) {
  59822. var _this = _super.call(this, name, scene) || this;
  59823. _this.generateOctree = false;
  59824. return _this;
  59825. }
  59826. GroundMesh.prototype.getClassName = function () {
  59827. return "GroundMesh";
  59828. };
  59829. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  59830. get: function () {
  59831. return Math.min(this._subdivisionsX, this._subdivisionsY);
  59832. },
  59833. enumerable: true,
  59834. configurable: true
  59835. });
  59836. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  59837. get: function () {
  59838. return this._subdivisionsX;
  59839. },
  59840. enumerable: true,
  59841. configurable: true
  59842. });
  59843. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  59844. get: function () {
  59845. return this._subdivisionsY;
  59846. },
  59847. enumerable: true,
  59848. configurable: true
  59849. });
  59850. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  59851. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  59852. this._subdivisionsX = chunksCount;
  59853. this._subdivisionsY = chunksCount;
  59854. this.subdivide(chunksCount);
  59855. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  59856. };
  59857. /**
  59858. * Returns a height (y) value in the Worl system :
  59859. * the ground altitude at the coordinates (x, z) expressed in the World system.
  59860. * Returns the ground y position if (x, z) are outside the ground surface.
  59861. */
  59862. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  59863. var world = this.getWorldMatrix();
  59864. var invMat = BABYLON.Tmp.Matrix[5];
  59865. world.invertToRef(invMat);
  59866. var tmpVect = BABYLON.Tmp.Vector3[8];
  59867. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  59868. x = tmpVect.x;
  59869. z = tmpVect.z;
  59870. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59871. return this.position.y;
  59872. }
  59873. if (!this._heightQuads || this._heightQuads.length == 0) {
  59874. this._initHeightQuads();
  59875. this._computeHeightQuads();
  59876. }
  59877. var facet = this._getFacetAt(x, z);
  59878. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  59879. // return y in the World system
  59880. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  59881. return tmpVect.y;
  59882. };
  59883. /**
  59884. * Returns a normalized vector (Vector3) orthogonal to the ground
  59885. * at the ground coordinates (x, z) expressed in the World system.
  59886. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  59887. */
  59888. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  59889. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  59890. this.getNormalAtCoordinatesToRef(x, z, normal);
  59891. return normal;
  59892. };
  59893. /**
  59894. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  59895. * at the ground coordinates (x, z) expressed in the World system.
  59896. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  59897. * Returns the GroundMesh.
  59898. */
  59899. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  59900. var world = this.getWorldMatrix();
  59901. var tmpMat = BABYLON.Tmp.Matrix[5];
  59902. world.invertToRef(tmpMat);
  59903. var tmpVect = BABYLON.Tmp.Vector3[8];
  59904. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  59905. x = tmpVect.x;
  59906. z = tmpVect.z;
  59907. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59908. return this;
  59909. }
  59910. if (!this._heightQuads || this._heightQuads.length == 0) {
  59911. this._initHeightQuads();
  59912. this._computeHeightQuads();
  59913. }
  59914. var facet = this._getFacetAt(x, z);
  59915. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  59916. return this;
  59917. };
  59918. /**
  59919. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  59920. * if the ground has been updated.
  59921. * This can be used in the render loop.
  59922. * Returns the GroundMesh.
  59923. */
  59924. GroundMesh.prototype.updateCoordinateHeights = function () {
  59925. if (!this._heightQuads || this._heightQuads.length == 0) {
  59926. this._initHeightQuads();
  59927. }
  59928. this._computeHeightQuads();
  59929. return this;
  59930. };
  59931. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  59932. GroundMesh.prototype._getFacetAt = function (x, z) {
  59933. // retrieve col and row from x, z coordinates in the ground local system
  59934. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  59935. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  59936. var quad = this._heightQuads[row * this._subdivisionsX + col];
  59937. var facet;
  59938. if (z < quad.slope.x * x + quad.slope.y) {
  59939. facet = quad.facet1;
  59940. }
  59941. else {
  59942. facet = quad.facet2;
  59943. }
  59944. return facet;
  59945. };
  59946. // Creates and populates the heightMap array with "facet" elements :
  59947. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  59948. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  59949. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  59950. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  59951. // Returns the GroundMesh.
  59952. GroundMesh.prototype._initHeightQuads = function () {
  59953. var subdivisionsX = this._subdivisionsX;
  59954. var subdivisionsY = this._subdivisionsY;
  59955. this._heightQuads = new Array();
  59956. for (var row = 0; row < subdivisionsY; row++) {
  59957. for (var col = 0; col < subdivisionsX; col++) {
  59958. 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) };
  59959. this._heightQuads[row * subdivisionsX + col] = quad;
  59960. }
  59961. }
  59962. return this;
  59963. };
  59964. // Compute each quad element values and update the the heightMap array :
  59965. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  59966. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  59967. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  59968. // Returns the GroundMesh.
  59969. GroundMesh.prototype._computeHeightQuads = function () {
  59970. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  59971. if (!positions) {
  59972. return this;
  59973. }
  59974. var v1 = BABYLON.Tmp.Vector3[3];
  59975. var v2 = BABYLON.Tmp.Vector3[2];
  59976. var v3 = BABYLON.Tmp.Vector3[1];
  59977. var v4 = BABYLON.Tmp.Vector3[0];
  59978. var v1v2 = BABYLON.Tmp.Vector3[4];
  59979. var v1v3 = BABYLON.Tmp.Vector3[5];
  59980. var v1v4 = BABYLON.Tmp.Vector3[6];
  59981. var norm1 = BABYLON.Tmp.Vector3[7];
  59982. var norm2 = BABYLON.Tmp.Vector3[8];
  59983. var i = 0;
  59984. var j = 0;
  59985. var k = 0;
  59986. var cd = 0; // 2D slope coefficient : z = cd * x + h
  59987. var h = 0;
  59988. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  59989. var d2 = 0;
  59990. var subdivisionsX = this._subdivisionsX;
  59991. var subdivisionsY = this._subdivisionsY;
  59992. for (var row = 0; row < subdivisionsY; row++) {
  59993. for (var col = 0; col < subdivisionsX; col++) {
  59994. i = col * 3;
  59995. j = row * (subdivisionsX + 1) * 3;
  59996. k = (row + 1) * (subdivisionsX + 1) * 3;
  59997. v1.x = positions[j + i];
  59998. v1.y = positions[j + i + 1];
  59999. v1.z = positions[j + i + 2];
  60000. v2.x = positions[j + i + 3];
  60001. v2.y = positions[j + i + 4];
  60002. v2.z = positions[j + i + 5];
  60003. v3.x = positions[k + i];
  60004. v3.y = positions[k + i + 1];
  60005. v3.z = positions[k + i + 2];
  60006. v4.x = positions[k + i + 3];
  60007. v4.y = positions[k + i + 4];
  60008. v4.z = positions[k + i + 5];
  60009. // 2D slope V1V4
  60010. cd = (v4.z - v1.z) / (v4.x - v1.x);
  60011. h = v1.z - cd * v1.x; // v1 belongs to the slope
  60012. // facet equations :
  60013. // we compute each facet normal vector
  60014. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  60015. // we compute the value d by applying the equation to v1 which belongs to the plane
  60016. // then we store the facet equation in a Vector4
  60017. v2.subtractToRef(v1, v1v2);
  60018. v3.subtractToRef(v1, v1v3);
  60019. v4.subtractToRef(v1, v1v4);
  60020. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  60021. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  60022. norm1.normalize();
  60023. norm2.normalize();
  60024. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  60025. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  60026. var quad = this._heightQuads[row * subdivisionsX + col];
  60027. quad.slope.copyFromFloats(cd, h);
  60028. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  60029. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  60030. }
  60031. }
  60032. return this;
  60033. };
  60034. GroundMesh.prototype.serialize = function (serializationObject) {
  60035. _super.prototype.serialize.call(this, serializationObject);
  60036. serializationObject.subdivisionsX = this._subdivisionsX;
  60037. serializationObject.subdivisionsY = this._subdivisionsY;
  60038. serializationObject.minX = this._minX;
  60039. serializationObject.maxX = this._maxX;
  60040. serializationObject.minZ = this._minZ;
  60041. serializationObject.maxZ = this._maxZ;
  60042. serializationObject.width = this._width;
  60043. serializationObject.height = this._height;
  60044. };
  60045. GroundMesh.Parse = function (parsedMesh, scene) {
  60046. var result = new GroundMesh(parsedMesh.name, scene);
  60047. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  60048. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  60049. result._minX = parsedMesh.minX;
  60050. result._maxX = parsedMesh.maxX;
  60051. result._minZ = parsedMesh.minZ;
  60052. result._maxZ = parsedMesh.maxZ;
  60053. result._width = parsedMesh.width;
  60054. result._height = parsedMesh.height;
  60055. return result;
  60056. };
  60057. return GroundMesh;
  60058. }(BABYLON.Mesh));
  60059. BABYLON.GroundMesh = GroundMesh;
  60060. })(BABYLON || (BABYLON = {}));
  60061. //# sourceMappingURL=babylon.groundMesh.js.map
  60062. var BABYLON;
  60063. (function (BABYLON) {
  60064. /**
  60065. * Creates an instance based on a source mesh.
  60066. */
  60067. var InstancedMesh = /** @class */ (function (_super) {
  60068. __extends(InstancedMesh, _super);
  60069. function InstancedMesh(name, source) {
  60070. var _this = _super.call(this, name, source.getScene()) || this;
  60071. source.instances.push(_this);
  60072. _this._sourceMesh = source;
  60073. _this.position.copyFrom(source.position);
  60074. _this.rotation.copyFrom(source.rotation);
  60075. _this.scaling.copyFrom(source.scaling);
  60076. if (source.rotationQuaternion) {
  60077. _this.rotationQuaternion = source.rotationQuaternion.clone();
  60078. }
  60079. _this.infiniteDistance = source.infiniteDistance;
  60080. _this.setPivotMatrix(source.getPivotMatrix());
  60081. _this.refreshBoundingInfo();
  60082. _this._syncSubMeshes();
  60083. return _this;
  60084. }
  60085. /**
  60086. * Returns the string "InstancedMesh".
  60087. */
  60088. InstancedMesh.prototype.getClassName = function () {
  60089. return "InstancedMesh";
  60090. };
  60091. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  60092. // Methods
  60093. get: function () {
  60094. return this._sourceMesh.receiveShadows;
  60095. },
  60096. enumerable: true,
  60097. configurable: true
  60098. });
  60099. Object.defineProperty(InstancedMesh.prototype, "material", {
  60100. get: function () {
  60101. return this._sourceMesh.material;
  60102. },
  60103. enumerable: true,
  60104. configurable: true
  60105. });
  60106. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  60107. get: function () {
  60108. return this._sourceMesh.visibility;
  60109. },
  60110. enumerable: true,
  60111. configurable: true
  60112. });
  60113. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  60114. get: function () {
  60115. return this._sourceMesh.skeleton;
  60116. },
  60117. enumerable: true,
  60118. configurable: true
  60119. });
  60120. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  60121. get: function () {
  60122. return this._sourceMesh.renderingGroupId;
  60123. },
  60124. set: function (value) {
  60125. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  60126. return;
  60127. }
  60128. //no-op with warning
  60129. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  60130. },
  60131. enumerable: true,
  60132. configurable: true
  60133. });
  60134. /**
  60135. * Returns the total number of vertices (integer).
  60136. */
  60137. InstancedMesh.prototype.getTotalVertices = function () {
  60138. return this._sourceMesh.getTotalVertices();
  60139. };
  60140. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  60141. get: function () {
  60142. return this._sourceMesh;
  60143. },
  60144. enumerable: true,
  60145. configurable: true
  60146. });
  60147. /**
  60148. * Is this node ready to be used/rendered
  60149. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  60150. * @return {boolean} is it ready
  60151. */
  60152. InstancedMesh.prototype.isReady = function (completeCheck) {
  60153. if (completeCheck === void 0) { completeCheck = false; }
  60154. return this._sourceMesh.isReady(completeCheck, true);
  60155. };
  60156. /**
  60157. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  60158. */
  60159. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  60160. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  60161. };
  60162. /**
  60163. * Sets the vertex data of the mesh geometry for the requested `kind`.
  60164. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  60165. * The `data` are either a numeric array either a Float32Array.
  60166. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  60167. * 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).
  60168. * Note that a new underlying VertexBuffer object is created each call.
  60169. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  60170. *
  60171. * Possible `kind` values :
  60172. * - BABYLON.VertexBuffer.PositionKind
  60173. * - BABYLON.VertexBuffer.UVKind
  60174. * - BABYLON.VertexBuffer.UV2Kind
  60175. * - BABYLON.VertexBuffer.UV3Kind
  60176. * - BABYLON.VertexBuffer.UV4Kind
  60177. * - BABYLON.VertexBuffer.UV5Kind
  60178. * - BABYLON.VertexBuffer.UV6Kind
  60179. * - BABYLON.VertexBuffer.ColorKind
  60180. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60181. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60182. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60183. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60184. *
  60185. * Returns the Mesh.
  60186. */
  60187. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  60188. if (this.sourceMesh) {
  60189. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  60190. }
  60191. return this.sourceMesh;
  60192. };
  60193. /**
  60194. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  60195. * If the mesh has no geometry, it is simply returned as it is.
  60196. * The `data` are either a numeric array either a Float32Array.
  60197. * No new underlying VertexBuffer object is created.
  60198. * 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.
  60199. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  60200. *
  60201. * Possible `kind` values :
  60202. * - BABYLON.VertexBuffer.PositionKind
  60203. * - BABYLON.VertexBuffer.UVKind
  60204. * - BABYLON.VertexBuffer.UV2Kind
  60205. * - BABYLON.VertexBuffer.UV3Kind
  60206. * - BABYLON.VertexBuffer.UV4Kind
  60207. * - BABYLON.VertexBuffer.UV5Kind
  60208. * - BABYLON.VertexBuffer.UV6Kind
  60209. * - BABYLON.VertexBuffer.ColorKind
  60210. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60211. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60212. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60213. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60214. *
  60215. * Returns the Mesh.
  60216. */
  60217. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  60218. if (this.sourceMesh) {
  60219. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  60220. }
  60221. return this.sourceMesh;
  60222. };
  60223. /**
  60224. * Sets the mesh indices.
  60225. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  60226. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  60227. * This method creates a new index buffer each call.
  60228. * Returns the Mesh.
  60229. */
  60230. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  60231. if (totalVertices === void 0) { totalVertices = null; }
  60232. if (this.sourceMesh) {
  60233. this.sourceMesh.setIndices(indices, totalVertices);
  60234. }
  60235. return this.sourceMesh;
  60236. };
  60237. /**
  60238. * Boolean : True if the mesh owns the requested kind of data.
  60239. */
  60240. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  60241. return this._sourceMesh.isVerticesDataPresent(kind);
  60242. };
  60243. /**
  60244. * Returns an array of indices (IndicesArray).
  60245. */
  60246. InstancedMesh.prototype.getIndices = function () {
  60247. return this._sourceMesh.getIndices();
  60248. };
  60249. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  60250. get: function () {
  60251. return this._sourceMesh._positions;
  60252. },
  60253. enumerable: true,
  60254. configurable: true
  60255. });
  60256. /**
  60257. * Sets a new updated BoundingInfo to the mesh.
  60258. * Returns the mesh.
  60259. */
  60260. InstancedMesh.prototype.refreshBoundingInfo = function () {
  60261. var meshBB = this._sourceMesh.getBoundingInfo();
  60262. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  60263. this._updateBoundingInfo();
  60264. return this;
  60265. };
  60266. InstancedMesh.prototype._preActivate = function () {
  60267. if (this._currentLOD) {
  60268. this._currentLOD._preActivate();
  60269. }
  60270. return this;
  60271. };
  60272. InstancedMesh.prototype._activate = function (renderId) {
  60273. if (this._currentLOD) {
  60274. this._currentLOD._registerInstanceForRenderId(this, renderId);
  60275. }
  60276. return this;
  60277. };
  60278. /**
  60279. * Returns the current associated LOD AbstractMesh.
  60280. */
  60281. InstancedMesh.prototype.getLOD = function (camera) {
  60282. if (!camera) {
  60283. return this;
  60284. }
  60285. var boundingInfo = this.getBoundingInfo();
  60286. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  60287. if (this._currentLOD === this.sourceMesh) {
  60288. return this;
  60289. }
  60290. return this._currentLOD;
  60291. };
  60292. InstancedMesh.prototype._syncSubMeshes = function () {
  60293. this.releaseSubMeshes();
  60294. if (this._sourceMesh.subMeshes) {
  60295. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  60296. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  60297. }
  60298. }
  60299. return this;
  60300. };
  60301. InstancedMesh.prototype._generatePointsArray = function () {
  60302. return this._sourceMesh._generatePointsArray();
  60303. };
  60304. /**
  60305. * Creates a new InstancedMesh from the current mesh.
  60306. * - name (string) : the cloned mesh name
  60307. * - newParent (optional Node) : the optional Node to parent the clone to.
  60308. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  60309. *
  60310. * Returns the clone.
  60311. */
  60312. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60313. var result = this._sourceMesh.createInstance(name);
  60314. // Deep copy
  60315. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  60316. // Bounding info
  60317. this.refreshBoundingInfo();
  60318. // Parent
  60319. if (newParent) {
  60320. result.parent = newParent;
  60321. }
  60322. if (!doNotCloneChildren) {
  60323. // Children
  60324. for (var index = 0; index < this.getScene().meshes.length; index++) {
  60325. var mesh = this.getScene().meshes[index];
  60326. if (mesh.parent === this) {
  60327. mesh.clone(mesh.name, result);
  60328. }
  60329. }
  60330. }
  60331. result.computeWorldMatrix(true);
  60332. return result;
  60333. };
  60334. /**
  60335. * Disposes the InstancedMesh.
  60336. * Returns nothing.
  60337. */
  60338. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  60339. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  60340. // Remove from mesh
  60341. var index = this._sourceMesh.instances.indexOf(this);
  60342. this._sourceMesh.instances.splice(index, 1);
  60343. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  60344. };
  60345. return InstancedMesh;
  60346. }(BABYLON.AbstractMesh));
  60347. BABYLON.InstancedMesh = InstancedMesh;
  60348. })(BABYLON || (BABYLON = {}));
  60349. //# sourceMappingURL=babylon.instancedMesh.js.map
  60350. var BABYLON;
  60351. (function (BABYLON) {
  60352. var LinesMesh = /** @class */ (function (_super) {
  60353. __extends(LinesMesh, _super);
  60354. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  60355. if (scene === void 0) { scene = null; }
  60356. if (parent === void 0) { parent = null; }
  60357. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  60358. _this.useVertexColor = useVertexColor;
  60359. _this.useVertexAlpha = useVertexAlpha;
  60360. _this.color = new BABYLON.Color3(1, 1, 1);
  60361. _this.alpha = 1;
  60362. if (source) {
  60363. _this.color = source.color.clone();
  60364. _this.alpha = source.alpha;
  60365. _this.useVertexColor = source.useVertexColor;
  60366. _this.useVertexAlpha = source.useVertexAlpha;
  60367. }
  60368. _this._intersectionThreshold = 0.1;
  60369. var defines = [];
  60370. var options = {
  60371. attributes: [BABYLON.VertexBuffer.PositionKind],
  60372. uniforms: ["world", "viewProjection"],
  60373. needAlphaBlending: true,
  60374. defines: defines
  60375. };
  60376. if (useVertexAlpha === false) {
  60377. options.needAlphaBlending = false;
  60378. }
  60379. if (!useVertexColor) {
  60380. options.uniforms.push("color");
  60381. }
  60382. else {
  60383. options.defines.push("#define VERTEXCOLOR");
  60384. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  60385. }
  60386. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  60387. return _this;
  60388. }
  60389. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  60390. /**
  60391. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60392. * This margin is expressed in world space coordinates, so its value may vary.
  60393. * Default value is 0.1
  60394. * @returns the intersection Threshold value.
  60395. */
  60396. get: function () {
  60397. return this._intersectionThreshold;
  60398. },
  60399. /**
  60400. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60401. * This margin is expressed in world space coordinates, so its value may vary.
  60402. * @param value the new threshold to apply
  60403. */
  60404. set: function (value) {
  60405. if (this._intersectionThreshold === value) {
  60406. return;
  60407. }
  60408. this._intersectionThreshold = value;
  60409. if (this.geometry) {
  60410. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  60411. }
  60412. },
  60413. enumerable: true,
  60414. configurable: true
  60415. });
  60416. /**
  60417. * Returns the string "LineMesh"
  60418. */
  60419. LinesMesh.prototype.getClassName = function () {
  60420. return "LinesMesh";
  60421. };
  60422. Object.defineProperty(LinesMesh.prototype, "material", {
  60423. get: function () {
  60424. return this._colorShader;
  60425. },
  60426. set: function (value) {
  60427. // Do nothing
  60428. },
  60429. enumerable: true,
  60430. configurable: true
  60431. });
  60432. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  60433. get: function () {
  60434. return false;
  60435. },
  60436. enumerable: true,
  60437. configurable: true
  60438. });
  60439. LinesMesh.prototype.createInstance = function (name) {
  60440. throw new Error("LinesMeshes do not support createInstance.");
  60441. };
  60442. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  60443. if (!this._geometry) {
  60444. return this;
  60445. }
  60446. // VBOs
  60447. this._geometry._bind(this._colorShader.getEffect());
  60448. // Color
  60449. if (!this.useVertexColor) {
  60450. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  60451. }
  60452. return this;
  60453. };
  60454. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  60455. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  60456. return this;
  60457. }
  60458. var engine = this.getScene().getEngine();
  60459. // Draw order
  60460. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  60461. return this;
  60462. };
  60463. LinesMesh.prototype.dispose = function (doNotRecurse) {
  60464. this._colorShader.dispose();
  60465. _super.prototype.dispose.call(this, doNotRecurse);
  60466. };
  60467. /**
  60468. * Returns a new LineMesh object cloned from the current one.
  60469. */
  60470. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60471. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  60472. };
  60473. return LinesMesh;
  60474. }(BABYLON.Mesh));
  60475. BABYLON.LinesMesh = LinesMesh;
  60476. })(BABYLON || (BABYLON = {}));
  60477. //# sourceMappingURL=babylon.linesMesh.js.map
  60478. var BABYLON;
  60479. (function (BABYLON) {
  60480. /**
  60481. * Class containing static functions to help procedurally build meshes
  60482. */
  60483. var MeshBuilder = /** @class */ (function () {
  60484. function MeshBuilder() {
  60485. }
  60486. MeshBuilder.updateSideOrientation = function (orientation) {
  60487. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  60488. return BABYLON.Mesh.DOUBLESIDE;
  60489. }
  60490. if (orientation === undefined || orientation === null) {
  60491. return BABYLON.Mesh.FRONTSIDE;
  60492. }
  60493. return orientation;
  60494. };
  60495. /**
  60496. * Creates a box mesh
  60497. * * The parameter `size` sets the size (float) of each box side (default 1)
  60498. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  60499. * * 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)
  60500. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  60501. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60502. * * 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
  60503. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60504. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  60505. * @param name defines the name of the mesh
  60506. * @param options defines the options used to create the mesh
  60507. * @param scene defines the hosting scene
  60508. * @returns the box mesh
  60509. */
  60510. MeshBuilder.CreateBox = function (name, options, scene) {
  60511. if (scene === void 0) { scene = null; }
  60512. var box = new BABYLON.Mesh(name, scene);
  60513. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60514. box._originalBuilderSideOrientation = options.sideOrientation;
  60515. var vertexData = BABYLON.VertexData.CreateBox(options);
  60516. vertexData.applyToMesh(box, options.updatable);
  60517. return box;
  60518. };
  60519. /**
  60520. * Creates a sphere mesh
  60521. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  60522. * * 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`)
  60523. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  60524. * * 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
  60525. * * 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)
  60526. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60527. * * 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
  60528. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60529. * @param name defines the name of the mesh
  60530. * @param options defines the options used to create the mesh
  60531. * @param scene defines the hosting scene
  60532. * @returns the sphere mesh
  60533. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  60534. */
  60535. MeshBuilder.CreateSphere = function (name, options, scene) {
  60536. var sphere = new BABYLON.Mesh(name, scene);
  60537. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60538. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60539. var vertexData = BABYLON.VertexData.CreateSphere(options);
  60540. vertexData.applyToMesh(sphere, options.updatable);
  60541. return sphere;
  60542. };
  60543. /**
  60544. * Creates a plane polygonal mesh. By default, this is a disc
  60545. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  60546. * * 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
  60547. * * 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
  60548. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60549. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60550. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60551. * @param name defines the name of the mesh
  60552. * @param options defines the options used to create the mesh
  60553. * @param scene defines the hosting scene
  60554. * @returns the plane polygonal mesh
  60555. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  60556. */
  60557. MeshBuilder.CreateDisc = function (name, options, scene) {
  60558. if (scene === void 0) { scene = null; }
  60559. var disc = new BABYLON.Mesh(name, scene);
  60560. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60561. disc._originalBuilderSideOrientation = options.sideOrientation;
  60562. var vertexData = BABYLON.VertexData.CreateDisc(options);
  60563. vertexData.applyToMesh(disc, options.updatable);
  60564. return disc;
  60565. };
  60566. /**
  60567. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  60568. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  60569. * * 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`)
  60570. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  60571. * * 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
  60572. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60573. * * 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
  60574. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60575. * @param name defines the name of the mesh
  60576. * @param options defines the options used to create the mesh
  60577. * @param scene defines the hosting scene
  60578. * @returns the icosahedron mesh
  60579. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  60580. */
  60581. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  60582. var sphere = new BABYLON.Mesh(name, scene);
  60583. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60584. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60585. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  60586. vertexData.applyToMesh(sphere, options.updatable);
  60587. return sphere;
  60588. };
  60589. ;
  60590. /**
  60591. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  60592. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  60593. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  60594. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  60595. * * 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
  60596. * * 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
  60597. * * 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
  60598. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60599. * * 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
  60600. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60601. * * 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
  60602. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  60603. * * 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
  60604. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  60605. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60606. * @param name defines the name of the mesh
  60607. * @param options defines the options used to create the mesh
  60608. * @param scene defines the hosting scene
  60609. * @returns the ribbon mesh
  60610. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  60611. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60612. */
  60613. MeshBuilder.CreateRibbon = function (name, options, scene) {
  60614. if (scene === void 0) { scene = null; }
  60615. var pathArray = options.pathArray;
  60616. var closeArray = options.closeArray;
  60617. var closePath = options.closePath;
  60618. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60619. var instance = options.instance;
  60620. var updatable = options.updatable;
  60621. if (instance) { // existing ribbon instance update
  60622. // positionFunction : ribbon case
  60623. // only pathArray and sideOrientation parameters are taken into account for positions update
  60624. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  60625. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  60626. var positionFunction = function (positions) {
  60627. var minlg = pathArray[0].length;
  60628. var i = 0;
  60629. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  60630. for (var si = 1; si <= ns; si++) {
  60631. for (var p = 0; p < pathArray.length; p++) {
  60632. var path = pathArray[p];
  60633. var l = path.length;
  60634. minlg = (minlg < l) ? minlg : l;
  60635. var j = 0;
  60636. while (j < minlg) {
  60637. positions[i] = path[j].x;
  60638. positions[i + 1] = path[j].y;
  60639. positions[i + 2] = path[j].z;
  60640. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  60641. BABYLON.Tmp.Vector3[0].x = path[j].x;
  60642. }
  60643. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  60644. BABYLON.Tmp.Vector3[1].x = path[j].x;
  60645. }
  60646. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  60647. BABYLON.Tmp.Vector3[0].y = path[j].y;
  60648. }
  60649. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  60650. BABYLON.Tmp.Vector3[1].y = path[j].y;
  60651. }
  60652. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  60653. BABYLON.Tmp.Vector3[0].z = path[j].z;
  60654. }
  60655. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  60656. BABYLON.Tmp.Vector3[1].z = path[j].z;
  60657. }
  60658. j++;
  60659. i += 3;
  60660. }
  60661. if (instance._closePath) {
  60662. positions[i] = path[0].x;
  60663. positions[i + 1] = path[0].y;
  60664. positions[i + 2] = path[0].z;
  60665. i += 3;
  60666. }
  60667. }
  60668. }
  60669. };
  60670. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60671. positionFunction(positions);
  60672. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  60673. instance._boundingInfo.update(instance._worldMatrix);
  60674. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  60675. if (options.colors) {
  60676. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  60677. for (var c = 0; c < options.colors.length; c++) {
  60678. colors[c * 4] = options.colors[c].r;
  60679. colors[c * 4 + 1] = options.colors[c].g;
  60680. colors[c * 4 + 2] = options.colors[c].b;
  60681. colors[c * 4 + 3] = options.colors[c].a;
  60682. }
  60683. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  60684. }
  60685. if (options.uvs) {
  60686. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  60687. for (var i = 0; i < options.uvs.length; i++) {
  60688. uvs[i * 2] = options.uvs[i].x;
  60689. uvs[i * 2 + 1] = options.uvs[i].y;
  60690. }
  60691. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  60692. }
  60693. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  60694. var indices = instance.getIndices();
  60695. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  60696. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  60697. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  60698. if (instance._closePath) {
  60699. var indexFirst = 0;
  60700. var indexLast = 0;
  60701. for (var p = 0; p < pathArray.length; p++) {
  60702. indexFirst = instance._idx[p] * 3;
  60703. if (p + 1 < pathArray.length) {
  60704. indexLast = (instance._idx[p + 1] - 1) * 3;
  60705. }
  60706. else {
  60707. indexLast = normals.length - 3;
  60708. }
  60709. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  60710. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  60711. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  60712. normals[indexLast] = normals[indexFirst];
  60713. normals[indexLast + 1] = normals[indexFirst + 1];
  60714. normals[indexLast + 2] = normals[indexFirst + 2];
  60715. }
  60716. }
  60717. if (!(instance.areNormalsFrozen)) {
  60718. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  60719. }
  60720. }
  60721. return instance;
  60722. }
  60723. else { // new ribbon creation
  60724. var ribbon = new BABYLON.Mesh(name, scene);
  60725. ribbon._originalBuilderSideOrientation = sideOrientation;
  60726. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  60727. if (closePath) {
  60728. ribbon._idx = vertexData._idx;
  60729. }
  60730. ribbon._closePath = closePath;
  60731. ribbon._closeArray = closeArray;
  60732. vertexData.applyToMesh(ribbon, updatable);
  60733. return ribbon;
  60734. }
  60735. };
  60736. /**
  60737. * Creates a cylinder or a cone mesh
  60738. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  60739. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  60740. * * 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.
  60741. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  60742. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  60743. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  60744. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  60745. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  60746. * * 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).
  60747. * * 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
  60748. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  60749. * * 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
  60750. * * 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.
  60751. * * If `enclose` is false, a ring surface is one element.
  60752. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  60753. * * 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
  60754. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60755. * * 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
  60756. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60757. * @param name defines the name of the mesh
  60758. * @param options defines the options used to create the mesh
  60759. * @param scene defines the hosting scene
  60760. * @returns the cylinder mesh
  60761. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  60762. */
  60763. MeshBuilder.CreateCylinder = function (name, options, scene) {
  60764. var cylinder = new BABYLON.Mesh(name, scene);
  60765. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60766. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  60767. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  60768. vertexData.applyToMesh(cylinder, options.updatable);
  60769. return cylinder;
  60770. };
  60771. /**
  60772. * Creates a torus mesh
  60773. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  60774. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  60775. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  60776. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60777. * * 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
  60778. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60779. * @param name defines the name of the mesh
  60780. * @param options defines the options used to create the mesh
  60781. * @param scene defines the hosting scene
  60782. * @returns the torus mesh
  60783. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  60784. */
  60785. MeshBuilder.CreateTorus = function (name, options, scene) {
  60786. var torus = new BABYLON.Mesh(name, scene);
  60787. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60788. torus._originalBuilderSideOrientation = options.sideOrientation;
  60789. var vertexData = BABYLON.VertexData.CreateTorus(options);
  60790. vertexData.applyToMesh(torus, options.updatable);
  60791. return torus;
  60792. };
  60793. /**
  60794. * Creates a torus knot mesh
  60795. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  60796. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  60797. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  60798. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  60799. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60800. * * 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
  60801. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60802. * @param name defines the name of the mesh
  60803. * @param options defines the options used to create the mesh
  60804. * @param scene defines the hosting scene
  60805. * @returns the torus knot mesh
  60806. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  60807. */
  60808. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  60809. var torusKnot = new BABYLON.Mesh(name, scene);
  60810. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60811. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  60812. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  60813. vertexData.applyToMesh(torusKnot, options.updatable);
  60814. return torusKnot;
  60815. };
  60816. /**
  60817. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  60818. * * 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
  60819. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  60820. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  60821. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  60822. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  60823. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  60824. * * 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
  60825. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  60826. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60827. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  60828. * @param name defines the name of the new line system
  60829. * @param options defines the options used to create the line system
  60830. * @param scene defines the hosting scene
  60831. * @returns a new line system mesh
  60832. */
  60833. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  60834. var instance = options.instance;
  60835. var lines = options.lines;
  60836. var colors = options.colors;
  60837. if (instance) { // lines update
  60838. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60839. var vertexColor;
  60840. var lineColors;
  60841. if (colors) {
  60842. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  60843. }
  60844. var i = 0;
  60845. var c = 0;
  60846. for (var l = 0; l < lines.length; l++) {
  60847. var points = lines[l];
  60848. for (var p = 0; p < points.length; p++) {
  60849. positions[i] = points[p].x;
  60850. positions[i + 1] = points[p].y;
  60851. positions[i + 2] = points[p].z;
  60852. if (colors && vertexColor) {
  60853. lineColors = colors[l];
  60854. vertexColor[c] = lineColors[p].r;
  60855. vertexColor[c + 1] = lineColors[p].g;
  60856. vertexColor[c + 2] = lineColors[p].b;
  60857. vertexColor[c + 3] = lineColors[p].a;
  60858. c += 4;
  60859. }
  60860. i += 3;
  60861. }
  60862. }
  60863. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  60864. if (colors && vertexColor) {
  60865. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  60866. }
  60867. return instance;
  60868. }
  60869. // line system creation
  60870. var useVertexColor = (colors) ? true : false;
  60871. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  60872. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  60873. vertexData.applyToMesh(lineSystem, options.updatable);
  60874. return lineSystem;
  60875. };
  60876. /**
  60877. * Creates a line mesh
  60878. * 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
  60879. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  60880. * * The parameter `points` is an array successive Vector3
  60881. * * 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
  60882. * * The optional parameter `colors` is an array of successive Color4, one per line point
  60883. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  60884. * * When updating an instance, remember that only point positions can change, not the number of points
  60885. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60886. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  60887. * @param name defines the name of the new line system
  60888. * @param options defines the options used to create the line system
  60889. * @param scene defines the hosting scene
  60890. * @returns a new line mesh
  60891. */
  60892. MeshBuilder.CreateLines = function (name, options, scene) {
  60893. if (scene === void 0) { scene = null; }
  60894. var colors = (options.colors) ? [options.colors] : null;
  60895. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  60896. return lines;
  60897. };
  60898. /**
  60899. * Creates a dashed line mesh
  60900. * * 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
  60901. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  60902. * * The parameter `points` is an array successive Vector3
  60903. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  60904. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  60905. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  60906. * * 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
  60907. * * When updating an instance, remember that only point positions can change, not the number of points
  60908. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60909. * @param name defines the name of the mesh
  60910. * @param options defines the options used to create the mesh
  60911. * @param scene defines the hosting scene
  60912. * @returns the dashed line mesh
  60913. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  60914. */
  60915. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  60916. if (scene === void 0) { scene = null; }
  60917. var points = options.points;
  60918. var instance = options.instance;
  60919. var gapSize = options.gapSize || 1;
  60920. var dashSize = options.dashSize || 3;
  60921. if (instance) { // dashed lines update
  60922. var positionFunction = function (positions) {
  60923. var curvect = BABYLON.Vector3.Zero();
  60924. var nbSeg = positions.length / 6;
  60925. var lg = 0;
  60926. var nb = 0;
  60927. var shft = 0;
  60928. var dashshft = 0;
  60929. var curshft = 0;
  60930. var p = 0;
  60931. var i = 0;
  60932. var j = 0;
  60933. for (i = 0; i < points.length - 1; i++) {
  60934. points[i + 1].subtractToRef(points[i], curvect);
  60935. lg += curvect.length();
  60936. }
  60937. shft = lg / nbSeg;
  60938. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  60939. for (i = 0; i < points.length - 1; i++) {
  60940. points[i + 1].subtractToRef(points[i], curvect);
  60941. nb = Math.floor(curvect.length() / shft);
  60942. curvect.normalize();
  60943. j = 0;
  60944. while (j < nb && p < positions.length) {
  60945. curshft = shft * j;
  60946. positions[p] = points[i].x + curshft * curvect.x;
  60947. positions[p + 1] = points[i].y + curshft * curvect.y;
  60948. positions[p + 2] = points[i].z + curshft * curvect.z;
  60949. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  60950. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  60951. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  60952. p += 6;
  60953. j++;
  60954. }
  60955. }
  60956. while (p < positions.length) {
  60957. positions[p] = points[i].x;
  60958. positions[p + 1] = points[i].y;
  60959. positions[p + 2] = points[i].z;
  60960. p += 3;
  60961. }
  60962. };
  60963. instance.updateMeshPositions(positionFunction, false);
  60964. return instance;
  60965. }
  60966. // dashed lines creation
  60967. var dashedLines = new BABYLON.LinesMesh(name, scene);
  60968. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  60969. vertexData.applyToMesh(dashedLines, options.updatable);
  60970. dashedLines.dashSize = dashSize;
  60971. dashedLines.gapSize = gapSize;
  60972. return dashedLines;
  60973. };
  60974. /**
  60975. * 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.
  60976. * * 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.
  60977. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  60978. * * 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.
  60979. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  60980. * * 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
  60981. * * 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
  60982. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  60983. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60984. * * 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
  60985. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  60986. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60987. * @param name defines the name of the mesh
  60988. * @param options defines the options used to create the mesh
  60989. * @param scene defines the hosting scene
  60990. * @returns the extruded shape mesh
  60991. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60992. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  60993. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  60994. */
  60995. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  60996. if (scene === void 0) { scene = null; }
  60997. var path = options.path;
  60998. var shape = options.shape;
  60999. var scale = options.scale || 1;
  61000. var rotation = options.rotation || 0;
  61001. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  61002. var updatable = options.updatable;
  61003. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61004. var instance = options.instance || null;
  61005. var invertUV = options.invertUV || false;
  61006. 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);
  61007. };
  61008. /**
  61009. * Creates an custom extruded shape mesh.
  61010. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  61011. * * 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.
  61012. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  61013. * * 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
  61014. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  61015. * * 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
  61016. * * It must returns a float value that will be the scale value applied to the shape on each path point
  61017. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  61018. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  61019. * * 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
  61020. * * 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
  61021. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  61022. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61023. * * 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
  61024. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61025. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61026. * @param name defines the name of the mesh
  61027. * @param options defines the options used to create the mesh
  61028. * @param scene defines the hosting scene
  61029. * @returns the custom extruded shape mesh
  61030. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  61031. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61032. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61033. */
  61034. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  61035. var path = options.path;
  61036. var shape = options.shape;
  61037. var scaleFunction = options.scaleFunction || (function () { return 1; });
  61038. var rotationFunction = options.rotationFunction || (function () { return 0; });
  61039. var ribbonCloseArray = options.ribbonCloseArray || false;
  61040. var ribbonClosePath = options.ribbonClosePath || false;
  61041. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  61042. var updatable = options.updatable;
  61043. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61044. var instance = options.instance;
  61045. var invertUV = options.invertUV || false;
  61046. 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);
  61047. };
  61048. /**
  61049. * Creates lathe mesh.
  61050. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  61051. * * 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
  61052. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  61053. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  61054. * * 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
  61055. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  61056. * * 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
  61057. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61058. * * 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
  61059. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61060. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61061. * @param name defines the name of the mesh
  61062. * @param options defines the options used to create the mesh
  61063. * @param scene defines the hosting scene
  61064. * @returns the lathe mesh
  61065. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  61066. */
  61067. MeshBuilder.CreateLathe = function (name, options, scene) {
  61068. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  61069. var closed = (options.closed === undefined) ? true : options.closed;
  61070. var shape = options.shape;
  61071. var radius = options.radius || 1;
  61072. var tessellation = options.tessellation || 64;
  61073. var updatable = options.updatable;
  61074. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61075. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61076. var pi2 = Math.PI * 2;
  61077. var paths = new Array();
  61078. var invertUV = options.invertUV || false;
  61079. var i = 0;
  61080. var p = 0;
  61081. var step = pi2 / tessellation * arc;
  61082. var rotated;
  61083. var path = new Array();
  61084. for (i = 0; i <= tessellation; i++) {
  61085. var path = [];
  61086. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  61087. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  61088. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  61089. }
  61090. for (p = 0; p < shape.length; p++) {
  61091. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  61092. path.push(rotated);
  61093. }
  61094. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  61095. 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));
  61096. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  61097. }
  61098. paths.push(path);
  61099. }
  61100. // lathe ribbon
  61101. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61102. return lathe;
  61103. };
  61104. /**
  61105. * Creates a plane mesh
  61106. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  61107. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  61108. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  61109. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61110. * * 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
  61111. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61112. * @param name defines the name of the mesh
  61113. * @param options defines the options used to create the mesh
  61114. * @param scene defines the hosting scene
  61115. * @returns the plane mesh
  61116. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61117. */
  61118. MeshBuilder.CreatePlane = function (name, options, scene) {
  61119. var plane = new BABYLON.Mesh(name, scene);
  61120. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61121. plane._originalBuilderSideOrientation = options.sideOrientation;
  61122. var vertexData = BABYLON.VertexData.CreatePlane(options);
  61123. vertexData.applyToMesh(plane, options.updatable);
  61124. if (options.sourcePlane) {
  61125. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  61126. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  61127. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  61128. plane.rotate(vectorProduct, product);
  61129. }
  61130. return plane;
  61131. };
  61132. /**
  61133. * Creates a ground mesh
  61134. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  61135. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  61136. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61137. * @param name defines the name of the mesh
  61138. * @param options defines the options used to create the mesh
  61139. * @param scene defines the hosting scene
  61140. * @returns the ground mesh
  61141. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61142. */
  61143. MeshBuilder.CreateGround = function (name, options, scene) {
  61144. var ground = new BABYLON.GroundMesh(name, scene);
  61145. ground._setReady(false);
  61146. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  61147. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  61148. ground._width = options.width || 1;
  61149. ground._height = options.height || 1;
  61150. ground._maxX = ground._width / 2;
  61151. ground._maxZ = ground._height / 2;
  61152. ground._minX = -ground._maxX;
  61153. ground._minZ = -ground._maxZ;
  61154. var vertexData = BABYLON.VertexData.CreateGround(options);
  61155. vertexData.applyToMesh(ground, options.updatable);
  61156. ground._setReady(true);
  61157. return ground;
  61158. };
  61159. /**
  61160. * Creates a tiled ground mesh
  61161. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  61162. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  61163. * * 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
  61164. * * 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
  61165. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61166. * @param name defines the name of the mesh
  61167. * @param options defines the options used to create the mesh
  61168. * @param scene defines the hosting scene
  61169. * @returns the tiled ground mesh
  61170. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  61171. */
  61172. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  61173. var tiledGround = new BABYLON.Mesh(name, scene);
  61174. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  61175. vertexData.applyToMesh(tiledGround, options.updatable);
  61176. return tiledGround;
  61177. };
  61178. /**
  61179. * Creates a ground mesh from a height map
  61180. * * The parameter `url` sets the URL of the height map image resource.
  61181. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  61182. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  61183. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  61184. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  61185. * * 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.
  61186. * * 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).
  61187. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61188. * @param name defines the name of the mesh
  61189. * @param url defines the url to the height map
  61190. * @param options defines the options used to create the mesh
  61191. * @param scene defines the hosting scene
  61192. * @returns the ground mesh
  61193. * @see http://doc.babylonjs.com/babylon101/height_map
  61194. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  61195. */
  61196. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  61197. var width = options.width || 10.0;
  61198. var height = options.height || 10.0;
  61199. var subdivisions = options.subdivisions || 1 | 0;
  61200. var minHeight = options.minHeight || 0.0;
  61201. var maxHeight = options.maxHeight || 1.0;
  61202. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  61203. var updatable = options.updatable;
  61204. var onReady = options.onReady;
  61205. var ground = new BABYLON.GroundMesh(name, scene);
  61206. ground._subdivisionsX = subdivisions;
  61207. ground._subdivisionsY = subdivisions;
  61208. ground._width = width;
  61209. ground._height = height;
  61210. ground._maxX = ground._width / 2.0;
  61211. ground._maxZ = ground._height / 2.0;
  61212. ground._minX = -ground._maxX;
  61213. ground._minZ = -ground._maxZ;
  61214. ground._setReady(false);
  61215. var onload = function (img) {
  61216. // Getting height map data
  61217. var canvas = document.createElement("canvas");
  61218. var context = canvas.getContext("2d");
  61219. if (!context) {
  61220. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  61221. }
  61222. if (scene.isDisposed) {
  61223. return;
  61224. }
  61225. var bufferWidth = img.width;
  61226. var bufferHeight = img.height;
  61227. canvas.width = bufferWidth;
  61228. canvas.height = bufferHeight;
  61229. context.drawImage(img, 0, 0);
  61230. // Create VertexData from map data
  61231. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  61232. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  61233. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  61234. width: width, height: height,
  61235. subdivisions: subdivisions,
  61236. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  61237. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  61238. });
  61239. vertexData.applyToMesh(ground, updatable);
  61240. //execute ready callback, if set
  61241. if (onReady) {
  61242. onReady(ground);
  61243. }
  61244. ground._setReady(true);
  61245. };
  61246. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  61247. return ground;
  61248. };
  61249. /**
  61250. * Creates a polygon mesh
  61251. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  61252. * * 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
  61253. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61254. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61255. * * 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)
  61256. * * Remember you can only change the shape positions, not their number when updating a polygon
  61257. * @param name defines the name of the mesh
  61258. * @param options defines the options used to create the mesh
  61259. * @param scene defines the hosting scene
  61260. * @returns the polygon mesh
  61261. */
  61262. MeshBuilder.CreatePolygon = function (name, options, scene) {
  61263. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61264. var shape = options.shape;
  61265. var holes = options.holes || [];
  61266. var depth = options.depth || 0;
  61267. var contours = [];
  61268. var hole = [];
  61269. for (var i = 0; i < shape.length; i++) {
  61270. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  61271. }
  61272. var epsilon = 0.00000001;
  61273. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  61274. contours.pop();
  61275. }
  61276. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  61277. for (var hNb = 0; hNb < holes.length; hNb++) {
  61278. hole = [];
  61279. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  61280. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  61281. }
  61282. polygonTriangulation.addHole(hole);
  61283. }
  61284. var polygon = polygonTriangulation.build(options.updatable, depth);
  61285. polygon._originalBuilderSideOrientation = options.sideOrientation;
  61286. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  61287. vertexData.applyToMesh(polygon, options.updatable);
  61288. return polygon;
  61289. };
  61290. ;
  61291. /**
  61292. * Creates an extruded polygon mesh, with depth in the Y direction.
  61293. * * 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)
  61294. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  61295. * @param name defines the name of the mesh
  61296. * @param options defines the options used to create the mesh
  61297. * @param scene defines the hosting scene
  61298. * @returns the polygon mesh
  61299. */
  61300. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  61301. return MeshBuilder.CreatePolygon(name, options, scene);
  61302. };
  61303. ;
  61304. /**
  61305. * Creates a tube mesh.
  61306. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  61307. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  61308. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  61309. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  61310. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  61311. * * 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)
  61312. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  61313. * * 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
  61314. * * 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
  61315. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61316. * * 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
  61317. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61318. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61319. * @param name defines the name of the mesh
  61320. * @param options defines the options used to create the mesh
  61321. * @param scene defines the hosting scene
  61322. * @returns the tube mesh
  61323. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61324. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  61325. */
  61326. MeshBuilder.CreateTube = function (name, options, scene) {
  61327. var path = options.path;
  61328. var instance = options.instance;
  61329. var radius = 1.0;
  61330. if (instance) {
  61331. radius = instance.radius;
  61332. }
  61333. if (options.radius !== undefined) {
  61334. radius = options.radius;
  61335. }
  61336. ;
  61337. var tessellation = options.tessellation || 64 | 0;
  61338. var radiusFunction = options.radiusFunction || null;
  61339. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61340. var invertUV = options.invertUV || false;
  61341. var updatable = options.updatable;
  61342. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61343. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  61344. // tube geometry
  61345. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  61346. var tangents = path3D.getTangents();
  61347. var normals = path3D.getNormals();
  61348. var distances = path3D.getDistances();
  61349. var pi2 = Math.PI * 2;
  61350. var step = pi2 / tessellation * arc;
  61351. var returnRadius = function () { return radius; };
  61352. var radiusFunctionFinal = radiusFunction || returnRadius;
  61353. var circlePath;
  61354. var rad;
  61355. var normal;
  61356. var rotated;
  61357. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61358. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61359. for (var i = 0; i < path.length; i++) {
  61360. rad = radiusFunctionFinal(i, distances[i]); // current radius
  61361. circlePath = Array(); // current circle array
  61362. normal = normals[i]; // current normal
  61363. for (var t = 0; t < tessellation; t++) {
  61364. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  61365. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  61366. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  61367. rotated.scaleInPlace(rad).addInPlace(path[i]);
  61368. circlePath[t] = rotated;
  61369. }
  61370. circlePaths[index] = circlePath;
  61371. index++;
  61372. }
  61373. // cap
  61374. var capPath = function (nbPoints, pathIndex) {
  61375. var pointCap = Array();
  61376. for (var i = 0; i < nbPoints; i++) {
  61377. pointCap.push(path[pathIndex]);
  61378. }
  61379. return pointCap;
  61380. };
  61381. switch (cap) {
  61382. case BABYLON.Mesh.NO_CAP:
  61383. break;
  61384. case BABYLON.Mesh.CAP_START:
  61385. circlePaths[0] = capPath(tessellation, 0);
  61386. circlePaths[1] = circlePaths[2].slice(0);
  61387. break;
  61388. case BABYLON.Mesh.CAP_END:
  61389. circlePaths[index] = circlePaths[index - 1].slice(0);
  61390. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61391. break;
  61392. case BABYLON.Mesh.CAP_ALL:
  61393. circlePaths[0] = capPath(tessellation, 0);
  61394. circlePaths[1] = circlePaths[2].slice(0);
  61395. circlePaths[index] = circlePaths[index - 1].slice(0);
  61396. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61397. break;
  61398. default:
  61399. break;
  61400. }
  61401. return circlePaths;
  61402. };
  61403. var path3D;
  61404. var pathArray;
  61405. if (instance) { // tube update
  61406. var arc = options.arc || instance.arc;
  61407. path3D = (instance.path3D).update(path);
  61408. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  61409. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  61410. instance.path3D = path3D;
  61411. instance.pathArray = pathArray;
  61412. instance.arc = arc;
  61413. instance.radius = radius;
  61414. return instance;
  61415. }
  61416. // tube creation
  61417. path3D = new BABYLON.Path3D(path);
  61418. var newPathArray = new Array();
  61419. cap = (cap < 0 || cap > 3) ? 0 : cap;
  61420. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  61421. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61422. tube.pathArray = pathArray;
  61423. tube.path3D = path3D;
  61424. tube.tessellation = tessellation;
  61425. tube.cap = cap;
  61426. tube.arc = options.arc;
  61427. tube.radius = radius;
  61428. return tube;
  61429. };
  61430. /**
  61431. * Creates a polyhedron mesh
  61432. * * 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
  61433. * * The parameter `size` (positive float, default 1) sets the polygon size
  61434. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  61435. * * 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`
  61436. * * 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
  61437. * * 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)`)
  61438. * * 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
  61439. * * 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
  61440. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61441. * * 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
  61442. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61443. * @param name defines the name of the mesh
  61444. * @param options defines the options used to create the mesh
  61445. * @param scene defines the hosting scene
  61446. * @returns the polyhedron mesh
  61447. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  61448. */
  61449. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  61450. var polyhedron = new BABYLON.Mesh(name, scene);
  61451. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61452. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  61453. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  61454. vertexData.applyToMesh(polyhedron, options.updatable);
  61455. return polyhedron;
  61456. };
  61457. /**
  61458. * Creates a decal mesh.
  61459. * 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
  61460. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  61461. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  61462. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  61463. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  61464. * @param name defines the name of the mesh
  61465. * @param sourceMesh defines the mesh where the decal must be applied
  61466. * @param options defines the options used to create the mesh
  61467. * @param scene defines the hosting scene
  61468. * @returns the decal mesh
  61469. * @see http://doc.babylonjs.com/how_to/decals
  61470. */
  61471. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  61472. var indices = sourceMesh.getIndices();
  61473. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61474. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  61475. var position = options.position || BABYLON.Vector3.Zero();
  61476. var normal = options.normal || BABYLON.Vector3.Up();
  61477. var size = options.size || BABYLON.Vector3.One();
  61478. var angle = options.angle || 0;
  61479. // Getting correct rotation
  61480. if (!normal) {
  61481. var target = new BABYLON.Vector3(0, 0, 1);
  61482. var camera = sourceMesh.getScene().activeCamera;
  61483. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  61484. normal = camera.globalPosition.subtract(cameraWorldTarget);
  61485. }
  61486. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  61487. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  61488. var pitch = Math.atan2(normal.y, len);
  61489. // Matrix
  61490. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  61491. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  61492. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  61493. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  61494. var vertexData = new BABYLON.VertexData();
  61495. vertexData.indices = [];
  61496. vertexData.positions = [];
  61497. vertexData.normals = [];
  61498. vertexData.uvs = [];
  61499. var currentVertexDataIndex = 0;
  61500. var extractDecalVector3 = function (indexId) {
  61501. var result = new BABYLON.PositionNormalVertex();
  61502. if (!indices || !positions || !normals) {
  61503. return result;
  61504. }
  61505. var vertexId = indices[indexId];
  61506. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  61507. // Send vector to decal local world
  61508. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  61509. // Get normal
  61510. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  61511. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  61512. return result;
  61513. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  61514. var clip = function (vertices, axis) {
  61515. if (vertices.length === 0) {
  61516. return vertices;
  61517. }
  61518. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  61519. var clipVertices = function (v0, v1) {
  61520. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  61521. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  61522. };
  61523. var result = new Array();
  61524. for (var index = 0; index < vertices.length; index += 3) {
  61525. var v1Out;
  61526. var v2Out;
  61527. var v3Out;
  61528. var total = 0;
  61529. var nV1 = null;
  61530. var nV2 = null;
  61531. var nV3 = null;
  61532. var nV4 = null;
  61533. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  61534. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  61535. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  61536. v1Out = d1 > 0;
  61537. v2Out = d2 > 0;
  61538. v3Out = d3 > 0;
  61539. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  61540. switch (total) {
  61541. case 0:
  61542. result.push(vertices[index]);
  61543. result.push(vertices[index + 1]);
  61544. result.push(vertices[index + 2]);
  61545. break;
  61546. case 1:
  61547. if (v1Out) {
  61548. nV1 = vertices[index + 1];
  61549. nV2 = vertices[index + 2];
  61550. nV3 = clipVertices(vertices[index], nV1);
  61551. nV4 = clipVertices(vertices[index], nV2);
  61552. }
  61553. if (v2Out) {
  61554. nV1 = vertices[index];
  61555. nV2 = vertices[index + 2];
  61556. nV3 = clipVertices(vertices[index + 1], nV1);
  61557. nV4 = clipVertices(vertices[index + 1], nV2);
  61558. result.push(nV3);
  61559. result.push(nV2.clone());
  61560. result.push(nV1.clone());
  61561. result.push(nV2.clone());
  61562. result.push(nV3.clone());
  61563. result.push(nV4);
  61564. break;
  61565. }
  61566. if (v3Out) {
  61567. nV1 = vertices[index];
  61568. nV2 = vertices[index + 1];
  61569. nV3 = clipVertices(vertices[index + 2], nV1);
  61570. nV4 = clipVertices(vertices[index + 2], nV2);
  61571. }
  61572. if (nV1 && nV2 && nV3 && nV4) {
  61573. result.push(nV1.clone());
  61574. result.push(nV2.clone());
  61575. result.push(nV3);
  61576. result.push(nV4);
  61577. result.push(nV3.clone());
  61578. result.push(nV2.clone());
  61579. }
  61580. break;
  61581. case 2:
  61582. if (!v1Out) {
  61583. nV1 = vertices[index].clone();
  61584. nV2 = clipVertices(nV1, vertices[index + 1]);
  61585. nV3 = clipVertices(nV1, vertices[index + 2]);
  61586. result.push(nV1);
  61587. result.push(nV2);
  61588. result.push(nV3);
  61589. }
  61590. if (!v2Out) {
  61591. nV1 = vertices[index + 1].clone();
  61592. nV2 = clipVertices(nV1, vertices[index + 2]);
  61593. nV3 = clipVertices(nV1, vertices[index]);
  61594. result.push(nV1);
  61595. result.push(nV2);
  61596. result.push(nV3);
  61597. }
  61598. if (!v3Out) {
  61599. nV1 = vertices[index + 2].clone();
  61600. nV2 = clipVertices(nV1, vertices[index]);
  61601. nV3 = clipVertices(nV1, vertices[index + 1]);
  61602. result.push(nV1);
  61603. result.push(nV2);
  61604. result.push(nV3);
  61605. }
  61606. break;
  61607. case 3:
  61608. break;
  61609. }
  61610. }
  61611. return result;
  61612. };
  61613. for (var index = 0; index < indices.length; index += 3) {
  61614. var faceVertices = new Array();
  61615. faceVertices.push(extractDecalVector3(index));
  61616. faceVertices.push(extractDecalVector3(index + 1));
  61617. faceVertices.push(extractDecalVector3(index + 2));
  61618. // Clip
  61619. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  61620. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  61621. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  61622. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  61623. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  61624. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  61625. if (faceVertices.length === 0) {
  61626. continue;
  61627. }
  61628. // Add UVs and get back to world
  61629. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  61630. var vertex = faceVertices[vIndex];
  61631. //TODO check for Int32Array | Uint32Array | Uint16Array
  61632. vertexData.indices.push(currentVertexDataIndex);
  61633. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  61634. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  61635. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  61636. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  61637. currentVertexDataIndex++;
  61638. }
  61639. }
  61640. // Return mesh
  61641. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  61642. vertexData.applyToMesh(decal);
  61643. decal.position = position.clone();
  61644. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  61645. return decal;
  61646. };
  61647. // Privates
  61648. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  61649. // extrusion geometry
  61650. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  61651. var tangents = path3D.getTangents();
  61652. var normals = path3D.getNormals();
  61653. var binormals = path3D.getBinormals();
  61654. var distances = path3D.getDistances();
  61655. var angle = 0;
  61656. var returnScale = function () { return scale !== null ? scale : 1; };
  61657. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  61658. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  61659. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  61660. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61661. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61662. for (var i = 0; i < curve.length; i++) {
  61663. var shapePath = new Array();
  61664. var angleStep = rotate(i, distances[i]);
  61665. var scaleRatio = scl(i, distances[i]);
  61666. for (var p = 0; p < shape.length; p++) {
  61667. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  61668. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  61669. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  61670. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  61671. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  61672. shapePath[p] = rotated;
  61673. }
  61674. shapePaths[index] = shapePath;
  61675. angle += angleStep;
  61676. index++;
  61677. }
  61678. // cap
  61679. var capPath = function (shapePath) {
  61680. var pointCap = Array();
  61681. var barycenter = BABYLON.Vector3.Zero();
  61682. var i;
  61683. for (i = 0; i < shapePath.length; i++) {
  61684. barycenter.addInPlace(shapePath[i]);
  61685. }
  61686. barycenter.scaleInPlace(1.0 / shapePath.length);
  61687. for (i = 0; i < shapePath.length; i++) {
  61688. pointCap.push(barycenter);
  61689. }
  61690. return pointCap;
  61691. };
  61692. switch (cap) {
  61693. case BABYLON.Mesh.NO_CAP:
  61694. break;
  61695. case BABYLON.Mesh.CAP_START:
  61696. shapePaths[0] = capPath(shapePaths[2]);
  61697. shapePaths[1] = shapePaths[2];
  61698. break;
  61699. case BABYLON.Mesh.CAP_END:
  61700. shapePaths[index] = shapePaths[index - 1];
  61701. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  61702. break;
  61703. case BABYLON.Mesh.CAP_ALL:
  61704. shapePaths[0] = capPath(shapePaths[2]);
  61705. shapePaths[1] = shapePaths[2];
  61706. shapePaths[index] = shapePaths[index - 1];
  61707. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  61708. break;
  61709. default:
  61710. break;
  61711. }
  61712. return shapePaths;
  61713. };
  61714. var path3D;
  61715. var pathArray;
  61716. if (instance) { // instance update
  61717. path3D = (instance.path3D).update(curve);
  61718. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  61719. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  61720. return instance;
  61721. }
  61722. // extruded shape creation
  61723. path3D = new BABYLON.Path3D(curve);
  61724. var newShapePaths = new Array();
  61725. cap = (cap < 0 || cap > 3) ? 0 : cap;
  61726. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  61727. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  61728. extrudedGeneric.pathArray = pathArray;
  61729. extrudedGeneric.path3D = path3D;
  61730. extrudedGeneric.cap = cap;
  61731. return extrudedGeneric;
  61732. };
  61733. return MeshBuilder;
  61734. }());
  61735. BABYLON.MeshBuilder = MeshBuilder;
  61736. })(BABYLON || (BABYLON = {}));
  61737. //# sourceMappingURL=babylon.meshBuilder.js.map
  61738. var BABYLON;
  61739. (function (BABYLON) {
  61740. /**
  61741. * Draco compression (https://google.github.io/draco/)
  61742. */
  61743. var DracoCompression = /** @class */ (function () {
  61744. /**
  61745. * Constructor
  61746. */
  61747. function DracoCompression() {
  61748. }
  61749. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  61750. /**
  61751. * Returns true if the decoder is available.
  61752. */
  61753. get: function () {
  61754. if (typeof DracoDecoderModule !== "undefined") {
  61755. return true;
  61756. }
  61757. var decoder = DracoCompression.Configuration.decoder;
  61758. if (decoder) {
  61759. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  61760. return true;
  61761. }
  61762. if (decoder.fallbackUrl) {
  61763. return true;
  61764. }
  61765. }
  61766. return false;
  61767. },
  61768. enumerable: true,
  61769. configurable: true
  61770. });
  61771. /**
  61772. * Stop all async operations and release resources.
  61773. */
  61774. DracoCompression.prototype.dispose = function () {
  61775. };
  61776. /**
  61777. * Decode Draco compressed mesh data to vertex data.
  61778. * @param data The array buffer view for the Draco compression data
  61779. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  61780. * @returns A promise that resolves with the decoded vertex data
  61781. */
  61782. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  61783. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  61784. var module = wrappedModule.module;
  61785. var vertexData = new BABYLON.VertexData();
  61786. var buffer = new module.DecoderBuffer();
  61787. buffer.Init(data, data.byteLength);
  61788. var decoder = new module.Decoder();
  61789. var geometry;
  61790. var status;
  61791. try {
  61792. var type = decoder.GetEncodedGeometryType(buffer);
  61793. switch (type) {
  61794. case module.TRIANGULAR_MESH:
  61795. geometry = new module.Mesh();
  61796. status = decoder.DecodeBufferToMesh(buffer, geometry);
  61797. break;
  61798. case module.POINT_CLOUD:
  61799. geometry = new module.PointCloud();
  61800. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  61801. break;
  61802. default:
  61803. throw new Error("Invalid geometry type " + type);
  61804. }
  61805. if (!status.ok() || !geometry.ptr) {
  61806. throw new Error(status.error_msg());
  61807. }
  61808. var numPoints = geometry.num_points();
  61809. if (type === module.TRIANGULAR_MESH) {
  61810. var numFaces = geometry.num_faces();
  61811. var faceIndices = new module.DracoInt32Array();
  61812. try {
  61813. var indices = new Uint32Array(numFaces * 3);
  61814. for (var i = 0; i < numFaces; i++) {
  61815. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  61816. var offset = i * 3;
  61817. indices[offset + 0] = faceIndices.GetValue(0);
  61818. indices[offset + 1] = faceIndices.GetValue(1);
  61819. indices[offset + 2] = faceIndices.GetValue(2);
  61820. }
  61821. vertexData.indices = indices;
  61822. }
  61823. finally {
  61824. module.destroy(faceIndices);
  61825. }
  61826. }
  61827. for (var kind in attributes) {
  61828. var uniqueId = attributes[kind];
  61829. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  61830. var dracoData = new module.DracoFloat32Array();
  61831. try {
  61832. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  61833. var babylonData = new Float32Array(numPoints * attribute.num_components());
  61834. for (var i = 0; i < babylonData.length; i++) {
  61835. babylonData[i] = dracoData.GetValue(i);
  61836. }
  61837. vertexData.set(babylonData, kind);
  61838. }
  61839. finally {
  61840. module.destroy(dracoData);
  61841. }
  61842. }
  61843. }
  61844. finally {
  61845. if (geometry) {
  61846. module.destroy(geometry);
  61847. }
  61848. module.destroy(decoder);
  61849. module.destroy(buffer);
  61850. }
  61851. return vertexData;
  61852. });
  61853. };
  61854. DracoCompression._GetDecoderModule = function () {
  61855. if (!DracoCompression._DecoderModulePromise) {
  61856. var promise = null;
  61857. var config_1 = {};
  61858. if (typeof DracoDecoderModule !== "undefined") {
  61859. promise = Promise.resolve();
  61860. }
  61861. else {
  61862. var decoder = DracoCompression.Configuration.decoder;
  61863. if (decoder) {
  61864. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  61865. promise = Promise.all([
  61866. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  61867. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  61868. config_1.wasmBinary = data;
  61869. })
  61870. ]);
  61871. }
  61872. else if (decoder.fallbackUrl) {
  61873. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  61874. }
  61875. }
  61876. }
  61877. if (!promise) {
  61878. throw new Error("Draco decoder module is not available");
  61879. }
  61880. DracoCompression._DecoderModulePromise = promise.then(function () {
  61881. return new Promise(function (resolve) {
  61882. config_1.onModuleLoaded = function (decoderModule) {
  61883. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  61884. resolve({ module: decoderModule });
  61885. };
  61886. DracoDecoderModule(config_1);
  61887. });
  61888. });
  61889. }
  61890. return DracoCompression._DecoderModulePromise;
  61891. };
  61892. DracoCompression._LoadScriptAsync = function (url) {
  61893. return new Promise(function (resolve, reject) {
  61894. BABYLON.Tools.LoadScript(url, function () {
  61895. resolve();
  61896. }, function (message) {
  61897. reject(new Error(message));
  61898. });
  61899. });
  61900. };
  61901. DracoCompression._LoadFileAsync = function (url) {
  61902. return new Promise(function (resolve, reject) {
  61903. BABYLON.Tools.LoadFile(url, function (data) {
  61904. resolve(data);
  61905. }, undefined, undefined, true, function (request, exception) {
  61906. reject(exception);
  61907. });
  61908. });
  61909. };
  61910. /**
  61911. * The configuration.
  61912. */
  61913. DracoCompression.Configuration = {
  61914. decoder: {
  61915. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  61916. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  61917. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  61918. }
  61919. };
  61920. return DracoCompression;
  61921. }());
  61922. BABYLON.DracoCompression = DracoCompression;
  61923. })(BABYLON || (BABYLON = {}));
  61924. //# sourceMappingURL=babylon.dracoCompression.js.map
  61925. var BABYLON;
  61926. (function (BABYLON) {
  61927. var AudioEngine = /** @class */ (function () {
  61928. function AudioEngine() {
  61929. this._audioContext = null;
  61930. this._audioContextInitialized = false;
  61931. this.canUseWebAudio = false;
  61932. this.WarnedWebAudioUnsupported = false;
  61933. this.unlocked = false;
  61934. this.isMP3supported = false;
  61935. this.isOGGsupported = false;
  61936. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  61937. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  61938. this.canUseWebAudio = true;
  61939. }
  61940. var audioElem = document.createElement('audio');
  61941. try {
  61942. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  61943. this.isMP3supported = true;
  61944. }
  61945. }
  61946. catch (e) {
  61947. // protect error during capability check.
  61948. }
  61949. try {
  61950. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  61951. this.isOGGsupported = true;
  61952. }
  61953. }
  61954. catch (e) {
  61955. // protect error during capability check.
  61956. }
  61957. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  61958. this._unlockiOSaudio();
  61959. }
  61960. else {
  61961. this.unlocked = true;
  61962. }
  61963. }
  61964. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  61965. get: function () {
  61966. if (!this._audioContextInitialized) {
  61967. this._initializeAudioContext();
  61968. }
  61969. return this._audioContext;
  61970. },
  61971. enumerable: true,
  61972. configurable: true
  61973. });
  61974. AudioEngine.prototype._unlockiOSaudio = function () {
  61975. var _this = this;
  61976. var unlockaudio = function () {
  61977. if (!_this.audioContext) {
  61978. return;
  61979. }
  61980. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  61981. var source = _this.audioContext.createBufferSource();
  61982. source.buffer = buffer;
  61983. source.connect(_this.audioContext.destination);
  61984. source.start(0);
  61985. setTimeout(function () {
  61986. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  61987. _this.unlocked = true;
  61988. window.removeEventListener('touchend', unlockaudio, false);
  61989. if (_this.onAudioUnlocked) {
  61990. _this.onAudioUnlocked();
  61991. }
  61992. }
  61993. }, 0);
  61994. };
  61995. window.addEventListener('touchend', unlockaudio, false);
  61996. };
  61997. AudioEngine.prototype._initializeAudioContext = function () {
  61998. try {
  61999. if (this.canUseWebAudio) {
  62000. this._audioContext = new AudioContext();
  62001. // create a global volume gain node
  62002. this.masterGain = this._audioContext.createGain();
  62003. this.masterGain.gain.value = 1;
  62004. this.masterGain.connect(this._audioContext.destination);
  62005. this._audioContextInitialized = true;
  62006. }
  62007. }
  62008. catch (e) {
  62009. this.canUseWebAudio = false;
  62010. BABYLON.Tools.Error("Web Audio: " + e.message);
  62011. }
  62012. };
  62013. AudioEngine.prototype.dispose = function () {
  62014. if (this.canUseWebAudio && this._audioContextInitialized) {
  62015. if (this._connectedAnalyser && this._audioContext) {
  62016. this._connectedAnalyser.stopDebugCanvas();
  62017. this._connectedAnalyser.dispose();
  62018. this.masterGain.disconnect();
  62019. this.masterGain.connect(this._audioContext.destination);
  62020. this._connectedAnalyser = null;
  62021. }
  62022. this.masterGain.gain.value = 1;
  62023. }
  62024. this.WarnedWebAudioUnsupported = false;
  62025. };
  62026. AudioEngine.prototype.getGlobalVolume = function () {
  62027. if (this.canUseWebAudio && this._audioContextInitialized) {
  62028. return this.masterGain.gain.value;
  62029. }
  62030. else {
  62031. return -1;
  62032. }
  62033. };
  62034. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  62035. if (this.canUseWebAudio && this._audioContextInitialized) {
  62036. this.masterGain.gain.value = newVolume;
  62037. }
  62038. };
  62039. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  62040. if (this._connectedAnalyser) {
  62041. this._connectedAnalyser.stopDebugCanvas();
  62042. }
  62043. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  62044. this._connectedAnalyser = analyser;
  62045. this.masterGain.disconnect();
  62046. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  62047. }
  62048. };
  62049. return AudioEngine;
  62050. }());
  62051. BABYLON.AudioEngine = AudioEngine;
  62052. })(BABYLON || (BABYLON = {}));
  62053. //# sourceMappingURL=babylon.audioEngine.js.map
  62054. var BABYLON;
  62055. (function (BABYLON) {
  62056. var Sound = /** @class */ (function () {
  62057. /**
  62058. * Create a sound and attach it to a scene
  62059. * @param name Name of your sound
  62060. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  62061. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  62062. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  62063. */
  62064. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  62065. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  62066. var _this = this;
  62067. this.autoplay = false;
  62068. this.loop = false;
  62069. this.useCustomAttenuation = false;
  62070. this.spatialSound = false;
  62071. this.refDistance = 1;
  62072. this.rolloffFactor = 1;
  62073. this.maxDistance = 100;
  62074. this.distanceModel = "linear";
  62075. this._panningModel = "equalpower";
  62076. this._playbackRate = 1;
  62077. this._streaming = false;
  62078. this._startTime = 0;
  62079. this._startOffset = 0;
  62080. this._position = BABYLON.Vector3.Zero();
  62081. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  62082. this._volume = 1;
  62083. this._isReadyToPlay = false;
  62084. this.isPlaying = false;
  62085. this.isPaused = false;
  62086. this._isDirectional = false;
  62087. // Used if you'd like to create a directional sound.
  62088. // If not set, the sound will be omnidirectional
  62089. this._coneInnerAngle = 360;
  62090. this._coneOuterAngle = 360;
  62091. this._coneOuterGain = 0;
  62092. this._isOutputConnected = false;
  62093. this._urlType = "Unknown";
  62094. this.name = name;
  62095. this._scene = scene;
  62096. this._readyToPlayCallback = readyToPlayCallback;
  62097. // Default custom attenuation function is a linear attenuation
  62098. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  62099. if (currentDistance < maxDistance) {
  62100. return currentVolume * (1 - currentDistance / maxDistance);
  62101. }
  62102. else {
  62103. return 0;
  62104. }
  62105. };
  62106. if (options) {
  62107. this.autoplay = options.autoplay || false;
  62108. this.loop = options.loop || false;
  62109. // if volume === 0, we need another way to check this option
  62110. if (options.volume !== undefined) {
  62111. this._volume = options.volume;
  62112. }
  62113. this.spatialSound = options.spatialSound || false;
  62114. this.maxDistance = options.maxDistance || 100;
  62115. this.useCustomAttenuation = options.useCustomAttenuation || false;
  62116. this.rolloffFactor = options.rolloffFactor || 1;
  62117. this.refDistance = options.refDistance || 1;
  62118. this.distanceModel = options.distanceModel || "linear";
  62119. this._playbackRate = options.playbackRate || 1;
  62120. this._streaming = options.streaming || false;
  62121. }
  62122. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62123. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  62124. this._soundGain.gain.value = this._volume;
  62125. this._inputAudioNode = this._soundGain;
  62126. this._ouputAudioNode = this._soundGain;
  62127. if (this.spatialSound) {
  62128. this._createSpatialParameters();
  62129. }
  62130. this._scene.mainSoundTrack.AddSound(this);
  62131. var validParameter = true;
  62132. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  62133. if (urlOrArrayBuffer) {
  62134. try {
  62135. if (typeof (urlOrArrayBuffer) === "string")
  62136. this._urlType = "String";
  62137. if (Array.isArray(urlOrArrayBuffer))
  62138. this._urlType = "Array";
  62139. if (urlOrArrayBuffer instanceof ArrayBuffer)
  62140. this._urlType = "ArrayBuffer";
  62141. var urls = [];
  62142. var codecSupportedFound = false;
  62143. switch (this._urlType) {
  62144. case "ArrayBuffer":
  62145. if (urlOrArrayBuffer.byteLength > 0) {
  62146. codecSupportedFound = true;
  62147. this._soundLoaded(urlOrArrayBuffer);
  62148. }
  62149. break;
  62150. case "String":
  62151. urls.push(urlOrArrayBuffer);
  62152. case "Array":
  62153. if (urls.length === 0)
  62154. urls = urlOrArrayBuffer;
  62155. // If we found a supported format, we load it immediately and stop the loop
  62156. for (var i = 0; i < urls.length; i++) {
  62157. var url = urls[i];
  62158. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  62159. codecSupportedFound = true;
  62160. }
  62161. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  62162. codecSupportedFound = true;
  62163. }
  62164. if (url.indexOf(".wav", url.length - 4) !== -1) {
  62165. codecSupportedFound = true;
  62166. }
  62167. if (url.indexOf("blob:") !== -1) {
  62168. codecSupportedFound = true;
  62169. }
  62170. if (codecSupportedFound) {
  62171. // Loading sound using XHR2
  62172. if (!this._streaming) {
  62173. this._scene._loadFile(url, function (data) {
  62174. _this._soundLoaded(data);
  62175. }, undefined, true, true, function (exception) {
  62176. if (exception) {
  62177. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  62178. }
  62179. BABYLON.Tools.Error("Sound creation aborted.");
  62180. _this._scene.mainSoundTrack.RemoveSound(_this);
  62181. });
  62182. }
  62183. // Streaming sound using HTML5 Audio tag
  62184. else {
  62185. this._htmlAudioElement = new Audio(url);
  62186. this._htmlAudioElement.controls = false;
  62187. this._htmlAudioElement.loop = this.loop;
  62188. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  62189. this._htmlAudioElement.preload = "auto";
  62190. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  62191. _this._isReadyToPlay = true;
  62192. if (_this.autoplay) {
  62193. _this.play();
  62194. }
  62195. if (_this._readyToPlayCallback) {
  62196. _this._readyToPlayCallback();
  62197. }
  62198. });
  62199. document.body.appendChild(this._htmlAudioElement);
  62200. }
  62201. break;
  62202. }
  62203. }
  62204. break;
  62205. default:
  62206. validParameter = false;
  62207. break;
  62208. }
  62209. if (!validParameter) {
  62210. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  62211. }
  62212. else {
  62213. if (!codecSupportedFound) {
  62214. this._isReadyToPlay = true;
  62215. // Simulating a ready to play event to avoid breaking code path
  62216. if (this._readyToPlayCallback) {
  62217. window.setTimeout(function () {
  62218. if (_this._readyToPlayCallback) {
  62219. _this._readyToPlayCallback();
  62220. }
  62221. }, 1000);
  62222. }
  62223. }
  62224. }
  62225. }
  62226. catch (ex) {
  62227. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  62228. this._scene.mainSoundTrack.RemoveSound(this);
  62229. }
  62230. }
  62231. }
  62232. else {
  62233. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  62234. this._scene.mainSoundTrack.AddSound(this);
  62235. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  62236. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  62237. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  62238. }
  62239. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  62240. if (this._readyToPlayCallback) {
  62241. window.setTimeout(function () {
  62242. if (_this._readyToPlayCallback) {
  62243. _this._readyToPlayCallback();
  62244. }
  62245. }, 1000);
  62246. }
  62247. }
  62248. }
  62249. Sound.prototype.dispose = function () {
  62250. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62251. if (this.isPlaying) {
  62252. this.stop();
  62253. }
  62254. this._isReadyToPlay = false;
  62255. if (this.soundTrackId === -1) {
  62256. this._scene.mainSoundTrack.RemoveSound(this);
  62257. }
  62258. else {
  62259. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  62260. }
  62261. if (this._soundGain) {
  62262. this._soundGain.disconnect();
  62263. this._soundGain = null;
  62264. }
  62265. if (this._soundPanner) {
  62266. this._soundPanner.disconnect();
  62267. this._soundPanner = null;
  62268. }
  62269. if (this._soundSource) {
  62270. this._soundSource.disconnect();
  62271. this._soundSource = null;
  62272. }
  62273. this._audioBuffer = null;
  62274. if (this._htmlAudioElement) {
  62275. this._htmlAudioElement.pause();
  62276. this._htmlAudioElement.src = "";
  62277. document.body.removeChild(this._htmlAudioElement);
  62278. }
  62279. if (this._connectedMesh && this._registerFunc) {
  62280. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62281. this._connectedMesh = null;
  62282. }
  62283. }
  62284. };
  62285. Sound.prototype.isReady = function () {
  62286. return this._isReadyToPlay;
  62287. };
  62288. Sound.prototype._soundLoaded = function (audioData) {
  62289. var _this = this;
  62290. if (!BABYLON.Engine.audioEngine.audioContext) {
  62291. return;
  62292. }
  62293. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  62294. _this._audioBuffer = buffer;
  62295. _this._isReadyToPlay = true;
  62296. if (_this.autoplay) {
  62297. _this.play();
  62298. }
  62299. if (_this._readyToPlayCallback) {
  62300. _this._readyToPlayCallback();
  62301. }
  62302. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  62303. };
  62304. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  62305. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62306. this._audioBuffer = audioBuffer;
  62307. this._isReadyToPlay = true;
  62308. }
  62309. };
  62310. Sound.prototype.updateOptions = function (options) {
  62311. if (options) {
  62312. this.loop = options.loop || this.loop;
  62313. this.maxDistance = options.maxDistance || this.maxDistance;
  62314. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  62315. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  62316. this.refDistance = options.refDistance || this.refDistance;
  62317. this.distanceModel = options.distanceModel || this.distanceModel;
  62318. this._playbackRate = options.playbackRate || this._playbackRate;
  62319. this._updateSpatialParameters();
  62320. if (this.isPlaying) {
  62321. if (this._streaming) {
  62322. this._htmlAudioElement.playbackRate = this._playbackRate;
  62323. }
  62324. else {
  62325. if (this._soundSource) {
  62326. this._soundSource.playbackRate.value = this._playbackRate;
  62327. }
  62328. }
  62329. }
  62330. }
  62331. };
  62332. Sound.prototype._createSpatialParameters = function () {
  62333. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62334. if (this._scene.headphone) {
  62335. this._panningModel = "HRTF";
  62336. }
  62337. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  62338. this._updateSpatialParameters();
  62339. this._soundPanner.connect(this._ouputAudioNode);
  62340. this._inputAudioNode = this._soundPanner;
  62341. }
  62342. };
  62343. Sound.prototype._updateSpatialParameters = function () {
  62344. if (this.spatialSound && this._soundPanner) {
  62345. if (this.useCustomAttenuation) {
  62346. // Tricks to disable in a way embedded Web Audio attenuation
  62347. this._soundPanner.distanceModel = "linear";
  62348. this._soundPanner.maxDistance = Number.MAX_VALUE;
  62349. this._soundPanner.refDistance = 1;
  62350. this._soundPanner.rolloffFactor = 1;
  62351. this._soundPanner.panningModel = this._panningModel;
  62352. }
  62353. else {
  62354. this._soundPanner.distanceModel = this.distanceModel;
  62355. this._soundPanner.maxDistance = this.maxDistance;
  62356. this._soundPanner.refDistance = this.refDistance;
  62357. this._soundPanner.rolloffFactor = this.rolloffFactor;
  62358. this._soundPanner.panningModel = this._panningModel;
  62359. }
  62360. }
  62361. };
  62362. Sound.prototype.switchPanningModelToHRTF = function () {
  62363. this._panningModel = "HRTF";
  62364. this._switchPanningModel();
  62365. };
  62366. Sound.prototype.switchPanningModelToEqualPower = function () {
  62367. this._panningModel = "equalpower";
  62368. this._switchPanningModel();
  62369. };
  62370. Sound.prototype._switchPanningModel = function () {
  62371. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62372. this._soundPanner.panningModel = this._panningModel;
  62373. }
  62374. };
  62375. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  62376. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62377. if (this._isOutputConnected) {
  62378. this._ouputAudioNode.disconnect();
  62379. }
  62380. this._ouputAudioNode.connect(soundTrackAudioNode);
  62381. this._isOutputConnected = true;
  62382. }
  62383. };
  62384. /**
  62385. * Transform this sound into a directional source
  62386. * @param coneInnerAngle Size of the inner cone in degree
  62387. * @param coneOuterAngle Size of the outer cone in degree
  62388. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  62389. */
  62390. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  62391. if (coneOuterAngle < coneInnerAngle) {
  62392. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  62393. return;
  62394. }
  62395. this._coneInnerAngle = coneInnerAngle;
  62396. this._coneOuterAngle = coneOuterAngle;
  62397. this._coneOuterGain = coneOuterGain;
  62398. this._isDirectional = true;
  62399. if (this.isPlaying && this.loop) {
  62400. this.stop();
  62401. this.play();
  62402. }
  62403. };
  62404. Sound.prototype.setPosition = function (newPosition) {
  62405. this._position = newPosition;
  62406. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62407. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62408. }
  62409. };
  62410. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  62411. this._localDirection = newLocalDirection;
  62412. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  62413. this._updateDirection();
  62414. }
  62415. };
  62416. Sound.prototype._updateDirection = function () {
  62417. if (!this._connectedMesh || !this._soundPanner) {
  62418. return;
  62419. }
  62420. var mat = this._connectedMesh.getWorldMatrix();
  62421. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  62422. direction.normalize();
  62423. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  62424. };
  62425. Sound.prototype.updateDistanceFromListener = function () {
  62426. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  62427. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  62428. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  62429. }
  62430. };
  62431. Sound.prototype.setAttenuationFunction = function (callback) {
  62432. this._customAttenuationFunction = callback;
  62433. };
  62434. /**
  62435. * Play the sound
  62436. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  62437. * @param offset (optional) Start the sound setting it at a specific time
  62438. */
  62439. Sound.prototype.play = function (time, offset) {
  62440. var _this = this;
  62441. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  62442. try {
  62443. if (this._startOffset < 0) {
  62444. time = -this._startOffset;
  62445. this._startOffset = 0;
  62446. }
  62447. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62448. if (!this._soundSource || !this._streamingSource) {
  62449. if (this.spatialSound && this._soundPanner) {
  62450. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62451. if (this._isDirectional) {
  62452. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  62453. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  62454. this._soundPanner.coneOuterGain = this._coneOuterGain;
  62455. if (this._connectedMesh) {
  62456. this._updateDirection();
  62457. }
  62458. else {
  62459. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  62460. }
  62461. }
  62462. }
  62463. }
  62464. if (this._streaming) {
  62465. if (!this._streamingSource) {
  62466. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  62467. this._htmlAudioElement.onended = function () { _this._onended(); };
  62468. this._htmlAudioElement.playbackRate = this._playbackRate;
  62469. }
  62470. this._streamingSource.disconnect();
  62471. this._streamingSource.connect(this._inputAudioNode);
  62472. this._htmlAudioElement.play();
  62473. }
  62474. else {
  62475. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  62476. this._soundSource.buffer = this._audioBuffer;
  62477. this._soundSource.connect(this._inputAudioNode);
  62478. this._soundSource.loop = this.loop;
  62479. this._soundSource.playbackRate.value = this._playbackRate;
  62480. this._soundSource.onended = function () { _this._onended(); };
  62481. if (this._soundSource.buffer) {
  62482. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  62483. }
  62484. }
  62485. this._startTime = startTime;
  62486. this.isPlaying = true;
  62487. this.isPaused = false;
  62488. }
  62489. catch (ex) {
  62490. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  62491. }
  62492. }
  62493. };
  62494. Sound.prototype._onended = function () {
  62495. this.isPlaying = false;
  62496. if (this.onended) {
  62497. this.onended();
  62498. }
  62499. };
  62500. /**
  62501. * Stop the sound
  62502. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  62503. */
  62504. Sound.prototype.stop = function (time) {
  62505. if (this.isPlaying) {
  62506. if (this._streaming) {
  62507. this._htmlAudioElement.pause();
  62508. // Test needed for Firefox or it will generate an Invalid State Error
  62509. if (this._htmlAudioElement.currentTime > 0) {
  62510. this._htmlAudioElement.currentTime = 0;
  62511. }
  62512. }
  62513. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  62514. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62515. this._soundSource.stop(stopTime);
  62516. this._soundSource.onended = function () { };
  62517. if (!this.isPaused) {
  62518. this._startOffset = 0;
  62519. }
  62520. }
  62521. this.isPlaying = false;
  62522. }
  62523. };
  62524. Sound.prototype.pause = function () {
  62525. if (this.isPlaying) {
  62526. this.isPaused = true;
  62527. if (this._streaming) {
  62528. this._htmlAudioElement.pause();
  62529. }
  62530. else if (BABYLON.Engine.audioEngine.audioContext) {
  62531. this.stop(0);
  62532. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  62533. }
  62534. }
  62535. };
  62536. Sound.prototype.setVolume = function (newVolume, time) {
  62537. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  62538. if (time && BABYLON.Engine.audioEngine.audioContext) {
  62539. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  62540. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  62541. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  62542. }
  62543. else {
  62544. this._soundGain.gain.value = newVolume;
  62545. }
  62546. }
  62547. this._volume = newVolume;
  62548. };
  62549. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  62550. this._playbackRate = newPlaybackRate;
  62551. if (this.isPlaying) {
  62552. if (this._streaming) {
  62553. this._htmlAudioElement.playbackRate = this._playbackRate;
  62554. }
  62555. else if (this._soundSource) {
  62556. this._soundSource.playbackRate.value = this._playbackRate;
  62557. }
  62558. }
  62559. };
  62560. Sound.prototype.getVolume = function () {
  62561. return this._volume;
  62562. };
  62563. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  62564. var _this = this;
  62565. if (this._connectedMesh && this._registerFunc) {
  62566. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62567. this._registerFunc = null;
  62568. }
  62569. this._connectedMesh = meshToConnectTo;
  62570. if (!this.spatialSound) {
  62571. this.spatialSound = true;
  62572. this._createSpatialParameters();
  62573. if (this.isPlaying && this.loop) {
  62574. this.stop();
  62575. this.play();
  62576. }
  62577. }
  62578. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  62579. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  62580. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  62581. };
  62582. Sound.prototype.detachFromMesh = function () {
  62583. if (this._connectedMesh && this._registerFunc) {
  62584. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62585. this._registerFunc = null;
  62586. this._connectedMesh = null;
  62587. }
  62588. };
  62589. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  62590. if (!node.getBoundingInfo) {
  62591. return;
  62592. }
  62593. var mesh = node;
  62594. var boundingInfo = mesh.getBoundingInfo();
  62595. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  62596. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  62597. this._updateDirection();
  62598. }
  62599. };
  62600. Sound.prototype.clone = function () {
  62601. var _this = this;
  62602. if (!this._streaming) {
  62603. var setBufferAndRun = function () {
  62604. if (_this._isReadyToPlay) {
  62605. clonedSound._audioBuffer = _this.getAudioBuffer();
  62606. clonedSound._isReadyToPlay = true;
  62607. if (clonedSound.autoplay) {
  62608. clonedSound.play();
  62609. }
  62610. }
  62611. else {
  62612. window.setTimeout(setBufferAndRun, 300);
  62613. }
  62614. };
  62615. var currentOptions = {
  62616. autoplay: this.autoplay, loop: this.loop,
  62617. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  62618. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  62619. refDistance: this.refDistance, distanceModel: this.distanceModel
  62620. };
  62621. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  62622. if (this.useCustomAttenuation) {
  62623. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  62624. }
  62625. clonedSound.setPosition(this._position);
  62626. clonedSound.setPlaybackRate(this._playbackRate);
  62627. setBufferAndRun();
  62628. return clonedSound;
  62629. }
  62630. // Can't clone a streaming sound
  62631. else {
  62632. return null;
  62633. }
  62634. };
  62635. Sound.prototype.getAudioBuffer = function () {
  62636. return this._audioBuffer;
  62637. };
  62638. Sound.prototype.serialize = function () {
  62639. var serializationObject = {
  62640. name: this.name,
  62641. url: this.name,
  62642. autoplay: this.autoplay,
  62643. loop: this.loop,
  62644. volume: this._volume,
  62645. spatialSound: this.spatialSound,
  62646. maxDistance: this.maxDistance,
  62647. rolloffFactor: this.rolloffFactor,
  62648. refDistance: this.refDistance,
  62649. distanceModel: this.distanceModel,
  62650. playbackRate: this._playbackRate,
  62651. panningModel: this._panningModel,
  62652. soundTrackId: this.soundTrackId
  62653. };
  62654. if (this.spatialSound) {
  62655. if (this._connectedMesh)
  62656. serializationObject.connectedMeshId = this._connectedMesh.id;
  62657. serializationObject.position = this._position.asArray();
  62658. serializationObject.refDistance = this.refDistance;
  62659. serializationObject.distanceModel = this.distanceModel;
  62660. serializationObject.isDirectional = this._isDirectional;
  62661. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  62662. serializationObject.coneInnerAngle = this._coneInnerAngle;
  62663. serializationObject.coneOuterAngle = this._coneOuterAngle;
  62664. serializationObject.coneOuterGain = this._coneOuterGain;
  62665. }
  62666. return serializationObject;
  62667. };
  62668. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  62669. var soundName = parsedSound.name;
  62670. var soundUrl;
  62671. if (parsedSound.url) {
  62672. soundUrl = rootUrl + parsedSound.url;
  62673. }
  62674. else {
  62675. soundUrl = rootUrl + soundName;
  62676. }
  62677. var options = {
  62678. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  62679. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  62680. rolloffFactor: parsedSound.rolloffFactor,
  62681. refDistance: parsedSound.refDistance,
  62682. distanceModel: parsedSound.distanceModel,
  62683. playbackRate: parsedSound.playbackRate
  62684. };
  62685. var newSound;
  62686. if (!sourceSound) {
  62687. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  62688. scene._addPendingData(newSound);
  62689. }
  62690. else {
  62691. var setBufferAndRun = function () {
  62692. if (sourceSound._isReadyToPlay) {
  62693. newSound._audioBuffer = sourceSound.getAudioBuffer();
  62694. newSound._isReadyToPlay = true;
  62695. if (newSound.autoplay) {
  62696. newSound.play();
  62697. }
  62698. }
  62699. else {
  62700. window.setTimeout(setBufferAndRun, 300);
  62701. }
  62702. };
  62703. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  62704. setBufferAndRun();
  62705. }
  62706. if (parsedSound.position) {
  62707. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  62708. newSound.setPosition(soundPosition);
  62709. }
  62710. if (parsedSound.isDirectional) {
  62711. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  62712. if (parsedSound.localDirectionToMesh) {
  62713. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  62714. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  62715. }
  62716. }
  62717. if (parsedSound.connectedMeshId) {
  62718. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  62719. if (connectedMesh) {
  62720. newSound.attachToMesh(connectedMesh);
  62721. }
  62722. }
  62723. return newSound;
  62724. };
  62725. return Sound;
  62726. }());
  62727. BABYLON.Sound = Sound;
  62728. })(BABYLON || (BABYLON = {}));
  62729. //# sourceMappingURL=babylon.sound.js.map
  62730. var BABYLON;
  62731. (function (BABYLON) {
  62732. var SoundTrack = /** @class */ (function () {
  62733. function SoundTrack(scene, options) {
  62734. this.id = -1;
  62735. this._isMainTrack = false;
  62736. this._isInitialized = false;
  62737. this._scene = scene;
  62738. this.soundCollection = new Array();
  62739. this._options = options;
  62740. if (!this._isMainTrack) {
  62741. this._scene.soundTracks.push(this);
  62742. this.id = this._scene.soundTracks.length - 1;
  62743. }
  62744. }
  62745. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  62746. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62747. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  62748. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  62749. if (this._options) {
  62750. if (this._options.volume) {
  62751. this._outputAudioNode.gain.value = this._options.volume;
  62752. }
  62753. if (this._options.mainTrack) {
  62754. this._isMainTrack = this._options.mainTrack;
  62755. }
  62756. }
  62757. this._isInitialized = true;
  62758. }
  62759. };
  62760. SoundTrack.prototype.dispose = function () {
  62761. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  62762. if (this._connectedAnalyser) {
  62763. this._connectedAnalyser.stopDebugCanvas();
  62764. }
  62765. while (this.soundCollection.length) {
  62766. this.soundCollection[0].dispose();
  62767. }
  62768. if (this._outputAudioNode) {
  62769. this._outputAudioNode.disconnect();
  62770. }
  62771. this._outputAudioNode = null;
  62772. }
  62773. };
  62774. SoundTrack.prototype.AddSound = function (sound) {
  62775. if (!this._isInitialized) {
  62776. this._initializeSoundTrackAudioGraph();
  62777. }
  62778. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62779. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  62780. }
  62781. if (sound.soundTrackId) {
  62782. if (sound.soundTrackId === -1) {
  62783. this._scene.mainSoundTrack.RemoveSound(sound);
  62784. }
  62785. else {
  62786. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  62787. }
  62788. }
  62789. this.soundCollection.push(sound);
  62790. sound.soundTrackId = this.id;
  62791. };
  62792. SoundTrack.prototype.RemoveSound = function (sound) {
  62793. var index = this.soundCollection.indexOf(sound);
  62794. if (index !== -1) {
  62795. this.soundCollection.splice(index, 1);
  62796. }
  62797. };
  62798. SoundTrack.prototype.setVolume = function (newVolume) {
  62799. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62800. this._outputAudioNode.gain.value = newVolume;
  62801. }
  62802. };
  62803. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  62804. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62805. for (var i = 0; i < this.soundCollection.length; i++) {
  62806. this.soundCollection[i].switchPanningModelToHRTF();
  62807. }
  62808. }
  62809. };
  62810. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  62811. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62812. for (var i = 0; i < this.soundCollection.length; i++) {
  62813. this.soundCollection[i].switchPanningModelToEqualPower();
  62814. }
  62815. }
  62816. };
  62817. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  62818. if (this._connectedAnalyser) {
  62819. this._connectedAnalyser.stopDebugCanvas();
  62820. }
  62821. this._connectedAnalyser = analyser;
  62822. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62823. this._outputAudioNode.disconnect();
  62824. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  62825. }
  62826. };
  62827. return SoundTrack;
  62828. }());
  62829. BABYLON.SoundTrack = SoundTrack;
  62830. })(BABYLON || (BABYLON = {}));
  62831. //# sourceMappingURL=babylon.soundtrack.js.map
  62832. var BABYLON;
  62833. (function (BABYLON) {
  62834. /**
  62835. * Class used to work with sound analyzer using fast fourier transform (FFT)
  62836. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  62837. */
  62838. var Analyser = /** @class */ (function () {
  62839. /**
  62840. * Creates a new analyser
  62841. * @param scene defines hosting scene
  62842. */
  62843. function Analyser(scene) {
  62844. /**
  62845. * Gets or sets the smoothing
  62846. * @ignorenaming
  62847. */
  62848. this.SMOOTHING = 0.75;
  62849. /**
  62850. * Gets or sets the FFT table size
  62851. * @ignorenaming
  62852. */
  62853. this.FFT_SIZE = 512;
  62854. /**
  62855. * Gets or sets the bar graph amplitude
  62856. * @ignorenaming
  62857. */
  62858. this.BARGRAPHAMPLITUDE = 256;
  62859. /**
  62860. * Gets or sets the position of the debug canvas
  62861. * @ignorenaming
  62862. */
  62863. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  62864. /**
  62865. * Gets or sets the debug canvas size
  62866. * @ignorenaming
  62867. */
  62868. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  62869. this._scene = scene;
  62870. this._audioEngine = BABYLON.Engine.audioEngine;
  62871. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  62872. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  62873. this._webAudioAnalyser.minDecibels = -140;
  62874. this._webAudioAnalyser.maxDecibels = 0;
  62875. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  62876. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  62877. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  62878. }
  62879. }
  62880. /**
  62881. * Get the number of data values you will have to play with for the visualization
  62882. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  62883. * @returns a number
  62884. */
  62885. Analyser.prototype.getFrequencyBinCount = function () {
  62886. if (this._audioEngine.canUseWebAudio) {
  62887. return this._webAudioAnalyser.frequencyBinCount;
  62888. }
  62889. else {
  62890. return 0;
  62891. }
  62892. };
  62893. /**
  62894. * Gets the current frequency data as a byte array
  62895. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  62896. * @returns a Uint8Array
  62897. */
  62898. Analyser.prototype.getByteFrequencyData = function () {
  62899. if (this._audioEngine.canUseWebAudio) {
  62900. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62901. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62902. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  62903. }
  62904. return this._byteFreqs;
  62905. };
  62906. /**
  62907. * Gets the current waveform as a byte array
  62908. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  62909. * @returns a Uint8Array
  62910. */
  62911. Analyser.prototype.getByteTimeDomainData = function () {
  62912. if (this._audioEngine.canUseWebAudio) {
  62913. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62914. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62915. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  62916. }
  62917. return this._byteTime;
  62918. };
  62919. /**
  62920. * Gets the current frequency data as a float array
  62921. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  62922. * @returns a Float32Array
  62923. */
  62924. Analyser.prototype.getFloatFrequencyData = function () {
  62925. if (this._audioEngine.canUseWebAudio) {
  62926. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  62927. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  62928. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  62929. }
  62930. return this._floatFreqs;
  62931. };
  62932. /**
  62933. * Renders the debug canvas
  62934. */
  62935. Analyser.prototype.drawDebugCanvas = function () {
  62936. var _this = this;
  62937. if (this._audioEngine.canUseWebAudio) {
  62938. if (!this._debugCanvas) {
  62939. this._debugCanvas = document.createElement("canvas");
  62940. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  62941. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  62942. this._debugCanvas.style.position = "absolute";
  62943. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  62944. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  62945. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  62946. document.body.appendChild(this._debugCanvas);
  62947. this._registerFunc = function () {
  62948. _this.drawDebugCanvas();
  62949. };
  62950. this._scene.registerBeforeRender(this._registerFunc);
  62951. }
  62952. if (this._registerFunc && this._debugCanvasContext) {
  62953. var workingArray = this.getByteFrequencyData();
  62954. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  62955. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  62956. // Draw the frequency domain chart.
  62957. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  62958. var value = workingArray[i];
  62959. var percent = value / this.BARGRAPHAMPLITUDE;
  62960. var height = this.DEBUGCANVASSIZE.height * percent;
  62961. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  62962. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  62963. var hue = i / this.getFrequencyBinCount() * 360;
  62964. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  62965. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  62966. }
  62967. }
  62968. }
  62969. };
  62970. /**
  62971. * Stops rendering the debug canvas and removes it
  62972. */
  62973. Analyser.prototype.stopDebugCanvas = function () {
  62974. if (this._debugCanvas) {
  62975. if (this._registerFunc) {
  62976. this._scene.unregisterBeforeRender(this._registerFunc);
  62977. this._registerFunc = null;
  62978. }
  62979. document.body.removeChild(this._debugCanvas);
  62980. this._debugCanvas = null;
  62981. this._debugCanvasContext = null;
  62982. }
  62983. };
  62984. /**
  62985. * Connects two audio nodes
  62986. * @param inputAudioNode defines first node to connect
  62987. * @param outputAudioNode defines second node to connect
  62988. */
  62989. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  62990. if (this._audioEngine.canUseWebAudio) {
  62991. inputAudioNode.connect(this._webAudioAnalyser);
  62992. this._webAudioAnalyser.connect(outputAudioNode);
  62993. }
  62994. };
  62995. /**
  62996. * Releases all associated resources
  62997. */
  62998. Analyser.prototype.dispose = function () {
  62999. if (this._audioEngine.canUseWebAudio) {
  63000. this._webAudioAnalyser.disconnect();
  63001. }
  63002. };
  63003. return Analyser;
  63004. }());
  63005. BABYLON.Analyser = Analyser;
  63006. })(BABYLON || (BABYLON = {}));
  63007. //# sourceMappingURL=babylon.analyser.js.map
  63008. var BABYLON;
  63009. (function (BABYLON) {
  63010. var CubeTexture = /** @class */ (function (_super) {
  63011. __extends(CubeTexture, _super);
  63012. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  63013. if (extensions === void 0) { extensions = null; }
  63014. if (noMipmap === void 0) { noMipmap = false; }
  63015. if (files === void 0) { files = null; }
  63016. if (onLoad === void 0) { onLoad = null; }
  63017. if (onError === void 0) { onError = null; }
  63018. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  63019. if (prefiltered === void 0) { prefiltered = false; }
  63020. if (forcedExtension === void 0) { forcedExtension = null; }
  63021. var _this = _super.call(this, scene) || this;
  63022. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  63023. /**
  63024. * Gets or sets the center of the bounding box associated with the cube texture
  63025. * It must define where the camera used to render the texture was set
  63026. */
  63027. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63028. _this._rotationY = 0;
  63029. _this.name = rootUrl;
  63030. _this.url = rootUrl;
  63031. _this._noMipmap = noMipmap;
  63032. _this.hasAlpha = false;
  63033. _this._format = format;
  63034. _this._prefiltered = prefiltered;
  63035. _this.isCube = true;
  63036. _this._textureMatrix = BABYLON.Matrix.Identity();
  63037. if (prefiltered) {
  63038. _this.gammaSpace = false;
  63039. }
  63040. if (!rootUrl && !files) {
  63041. return _this;
  63042. }
  63043. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  63044. var lastDot = rootUrl.lastIndexOf(".");
  63045. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  63046. var isDDS = (extension === ".dds");
  63047. if (!files) {
  63048. if (!isDDS && !extensions) {
  63049. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  63050. }
  63051. files = [];
  63052. if (extensions) {
  63053. for (var index = 0; index < extensions.length; index++) {
  63054. files.push(rootUrl + extensions[index]);
  63055. }
  63056. }
  63057. }
  63058. _this._files = files;
  63059. if (!_this._texture) {
  63060. if (!scene.useDelayedTextureLoading) {
  63061. if (prefiltered) {
  63062. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  63063. }
  63064. else {
  63065. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  63066. }
  63067. }
  63068. else {
  63069. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  63070. }
  63071. }
  63072. else if (onLoad) {
  63073. if (_this._texture.isReady) {
  63074. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  63075. }
  63076. else {
  63077. _this._texture.onLoadedObservable.add(onLoad);
  63078. }
  63079. }
  63080. return _this;
  63081. }
  63082. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  63083. get: function () {
  63084. return this._boundingBoxSize;
  63085. },
  63086. /**
  63087. * Gets or sets the size of the bounding box associated with the cube texture
  63088. * When defined, the cubemap will switch to local mode
  63089. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63090. * @example https://www.babylonjs-playground.com/#RNASML
  63091. */
  63092. set: function (value) {
  63093. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63094. return;
  63095. }
  63096. this._boundingBoxSize = value;
  63097. var scene = this.getScene();
  63098. if (scene) {
  63099. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63100. }
  63101. },
  63102. enumerable: true,
  63103. configurable: true
  63104. });
  63105. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  63106. /**
  63107. * Gets texture matrix rotation angle around Y axis radians.
  63108. */
  63109. get: function () {
  63110. return this._rotationY;
  63111. },
  63112. /**
  63113. * Sets texture matrix rotation angle around Y axis in radians.
  63114. */
  63115. set: function (value) {
  63116. this._rotationY = value;
  63117. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  63118. },
  63119. enumerable: true,
  63120. configurable: true
  63121. });
  63122. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  63123. var rootUrlKey = "";
  63124. files.forEach(function (url) { return rootUrlKey += url; });
  63125. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  63126. };
  63127. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  63128. if (forcedExtension === void 0) { forcedExtension = null; }
  63129. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  63130. };
  63131. // Methods
  63132. CubeTexture.prototype.delayLoad = function () {
  63133. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  63134. return;
  63135. }
  63136. var scene = this.getScene();
  63137. if (!scene) {
  63138. return;
  63139. }
  63140. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  63141. this._texture = this._getFromCache(this.url, this._noMipmap);
  63142. if (!this._texture) {
  63143. if (this._prefiltered) {
  63144. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  63145. }
  63146. else {
  63147. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  63148. }
  63149. }
  63150. };
  63151. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  63152. return this._textureMatrix;
  63153. };
  63154. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  63155. this._textureMatrix = value;
  63156. };
  63157. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  63158. var texture = BABYLON.SerializationHelper.Parse(function () {
  63159. var prefiltered = false;
  63160. if (parsedTexture.prefiltered) {
  63161. prefiltered = parsedTexture.prefiltered;
  63162. }
  63163. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  63164. }, parsedTexture, scene);
  63165. // Local Cubemaps
  63166. if (parsedTexture.boundingBoxPosition) {
  63167. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  63168. }
  63169. if (parsedTexture.boundingBoxSize) {
  63170. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  63171. }
  63172. // Animations
  63173. if (parsedTexture.animations) {
  63174. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  63175. var parsedAnimation = parsedTexture.animations[animationIndex];
  63176. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  63177. }
  63178. }
  63179. return texture;
  63180. };
  63181. CubeTexture.prototype.clone = function () {
  63182. var _this = this;
  63183. return BABYLON.SerializationHelper.Clone(function () {
  63184. var scene = _this.getScene();
  63185. if (!scene) {
  63186. return _this;
  63187. }
  63188. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  63189. }, this);
  63190. };
  63191. __decorate([
  63192. BABYLON.serialize("rotationY")
  63193. ], CubeTexture.prototype, "_rotationY", void 0);
  63194. return CubeTexture;
  63195. }(BABYLON.BaseTexture));
  63196. BABYLON.CubeTexture = CubeTexture;
  63197. })(BABYLON || (BABYLON = {}));
  63198. //# sourceMappingURL=babylon.cubeTexture.js.map
  63199. var BABYLON;
  63200. (function (BABYLON) {
  63201. var RenderTargetTexture = /** @class */ (function (_super) {
  63202. __extends(RenderTargetTexture, _super);
  63203. /**
  63204. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  63205. * or used a shadow, depth texture...
  63206. * @param name The friendly name of the texture
  63207. * @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)
  63208. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  63209. * @param generateMipMaps True if mip maps need to be generated after render.
  63210. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  63211. * @param type The type of the buffer in the RTT (int, half float, float...)
  63212. * @param isCube True if a cube texture needs to be created
  63213. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  63214. * @param generateDepthBuffer True to generate a depth buffer
  63215. * @param generateStencilBuffer True to generate a stencil buffer
  63216. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  63217. */
  63218. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  63219. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  63220. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63221. if (isCube === void 0) { isCube = false; }
  63222. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63223. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  63224. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  63225. if (isMulti === void 0) { isMulti = false; }
  63226. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  63227. _this.isCube = isCube;
  63228. /**
  63229. * Use this list to define the list of mesh you want to render.
  63230. */
  63231. _this.renderList = new Array();
  63232. _this.renderParticles = true;
  63233. _this.renderSprites = false;
  63234. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  63235. _this.ignoreCameraViewport = false;
  63236. // Events
  63237. /**
  63238. * An event triggered when the texture is unbind.
  63239. */
  63240. _this.onBeforeBindObservable = new BABYLON.Observable();
  63241. /**
  63242. * An event triggered when the texture is unbind.
  63243. */
  63244. _this.onAfterUnbindObservable = new BABYLON.Observable();
  63245. /**
  63246. * An event triggered before rendering the texture
  63247. */
  63248. _this.onBeforeRenderObservable = new BABYLON.Observable();
  63249. /**
  63250. * An event triggered after rendering the texture
  63251. */
  63252. _this.onAfterRenderObservable = new BABYLON.Observable();
  63253. /**
  63254. * An event triggered after the texture clear
  63255. */
  63256. _this.onClearObservable = new BABYLON.Observable();
  63257. _this._currentRefreshId = -1;
  63258. _this._refreshRate = 1;
  63259. _this._samples = 1;
  63260. /**
  63261. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  63262. * It must define where the camera used to render the texture is set
  63263. */
  63264. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63265. scene = _this.getScene();
  63266. if (!scene) {
  63267. return _this;
  63268. }
  63269. _this._engine = scene.getEngine();
  63270. _this.name = name;
  63271. _this.isRenderTarget = true;
  63272. _this._initialSizeParameter = size;
  63273. _this._processSizeParameter(size);
  63274. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  63275. });
  63276. _this._generateMipMaps = generateMipMaps ? true : false;
  63277. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  63278. // Rendering groups
  63279. _this._renderingManager = new BABYLON.RenderingManager(scene);
  63280. if (isMulti) {
  63281. return _this;
  63282. }
  63283. _this._renderTargetOptions = {
  63284. generateMipMaps: generateMipMaps,
  63285. type: type,
  63286. samplingMode: samplingMode,
  63287. generateDepthBuffer: generateDepthBuffer,
  63288. generateStencilBuffer: generateStencilBuffer
  63289. };
  63290. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  63291. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63292. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63293. }
  63294. if (isCube) {
  63295. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  63296. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  63297. _this._textureMatrix = BABYLON.Matrix.Identity();
  63298. }
  63299. else {
  63300. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  63301. }
  63302. return _this;
  63303. }
  63304. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  63305. get: function () {
  63306. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  63307. },
  63308. enumerable: true,
  63309. configurable: true
  63310. });
  63311. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  63312. get: function () {
  63313. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  63314. },
  63315. enumerable: true,
  63316. configurable: true
  63317. });
  63318. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  63319. get: function () {
  63320. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  63321. },
  63322. enumerable: true,
  63323. configurable: true
  63324. });
  63325. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  63326. set: function (callback) {
  63327. if (this._onAfterUnbindObserver) {
  63328. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  63329. }
  63330. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  63331. },
  63332. enumerable: true,
  63333. configurable: true
  63334. });
  63335. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  63336. set: function (callback) {
  63337. if (this._onBeforeRenderObserver) {
  63338. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  63339. }
  63340. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  63341. },
  63342. enumerable: true,
  63343. configurable: true
  63344. });
  63345. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  63346. set: function (callback) {
  63347. if (this._onAfterRenderObserver) {
  63348. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  63349. }
  63350. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  63351. },
  63352. enumerable: true,
  63353. configurable: true
  63354. });
  63355. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  63356. set: function (callback) {
  63357. if (this._onClearObserver) {
  63358. this.onClearObservable.remove(this._onClearObserver);
  63359. }
  63360. this._onClearObserver = this.onClearObservable.add(callback);
  63361. },
  63362. enumerable: true,
  63363. configurable: true
  63364. });
  63365. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  63366. get: function () {
  63367. return this._renderTargetOptions;
  63368. },
  63369. enumerable: true,
  63370. configurable: true
  63371. });
  63372. RenderTargetTexture.prototype._onRatioRescale = function () {
  63373. if (this._sizeRatio) {
  63374. this.resize(this._initialSizeParameter);
  63375. }
  63376. };
  63377. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  63378. get: function () {
  63379. return this._boundingBoxSize;
  63380. },
  63381. /**
  63382. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  63383. * When defined, the cubemap will switch to local mode
  63384. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63385. * @example https://www.babylonjs-playground.com/#RNASML
  63386. */
  63387. set: function (value) {
  63388. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63389. return;
  63390. }
  63391. this._boundingBoxSize = value;
  63392. var scene = this.getScene();
  63393. if (scene) {
  63394. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63395. }
  63396. },
  63397. enumerable: true,
  63398. configurable: true
  63399. });
  63400. /**
  63401. * Creates a depth stencil texture.
  63402. * This is only available in WebGL 2 or with the depth texture extension available.
  63403. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  63404. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  63405. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  63406. */
  63407. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  63408. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  63409. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  63410. if (generateStencil === void 0) { generateStencil = false; }
  63411. if (!this.getScene()) {
  63412. return;
  63413. }
  63414. var engine = this.getScene().getEngine();
  63415. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  63416. bilinearFiltering: bilinearFiltering,
  63417. comparisonFunction: comparisonFunction,
  63418. generateStencil: generateStencil,
  63419. isCube: this.isCube
  63420. });
  63421. engine.setFrameBufferDepthStencilTexture(this);
  63422. };
  63423. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  63424. if (size.ratio) {
  63425. this._sizeRatio = size.ratio;
  63426. this._size = {
  63427. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  63428. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  63429. };
  63430. }
  63431. else {
  63432. this._size = size;
  63433. }
  63434. };
  63435. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  63436. get: function () {
  63437. return this._samples;
  63438. },
  63439. set: function (value) {
  63440. if (this._samples === value) {
  63441. return;
  63442. }
  63443. var scene = this.getScene();
  63444. if (!scene) {
  63445. return;
  63446. }
  63447. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  63448. },
  63449. enumerable: true,
  63450. configurable: true
  63451. });
  63452. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  63453. this._currentRefreshId = -1;
  63454. };
  63455. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  63456. get: function () {
  63457. return this._refreshRate;
  63458. },
  63459. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  63460. set: function (value) {
  63461. this._refreshRate = value;
  63462. this.resetRefreshCounter();
  63463. },
  63464. enumerable: true,
  63465. configurable: true
  63466. });
  63467. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  63468. if (!this._postProcessManager) {
  63469. var scene = this.getScene();
  63470. if (!scene) {
  63471. return;
  63472. }
  63473. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  63474. this._postProcesses = new Array();
  63475. }
  63476. this._postProcesses.push(postProcess);
  63477. this._postProcesses[0].autoClear = false;
  63478. };
  63479. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  63480. if (!this._postProcesses) {
  63481. return;
  63482. }
  63483. if (dispose) {
  63484. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  63485. var postProcess = _a[_i];
  63486. postProcess.dispose();
  63487. }
  63488. }
  63489. this._postProcesses = [];
  63490. };
  63491. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  63492. if (!this._postProcesses) {
  63493. return;
  63494. }
  63495. var index = this._postProcesses.indexOf(postProcess);
  63496. if (index === -1) {
  63497. return;
  63498. }
  63499. this._postProcesses.splice(index, 1);
  63500. if (this._postProcesses.length > 0) {
  63501. this._postProcesses[0].autoClear = false;
  63502. }
  63503. };
  63504. RenderTargetTexture.prototype._shouldRender = function () {
  63505. if (this._currentRefreshId === -1) { // At least render once
  63506. this._currentRefreshId = 1;
  63507. return true;
  63508. }
  63509. if (this.refreshRate === this._currentRefreshId) {
  63510. this._currentRefreshId = 1;
  63511. return true;
  63512. }
  63513. this._currentRefreshId++;
  63514. return false;
  63515. };
  63516. RenderTargetTexture.prototype.getRenderSize = function () {
  63517. if (this._size.width) {
  63518. return this._size.width;
  63519. }
  63520. return this._size;
  63521. };
  63522. RenderTargetTexture.prototype.getRenderWidth = function () {
  63523. if (this._size.width) {
  63524. return this._size.width;
  63525. }
  63526. return this._size;
  63527. };
  63528. RenderTargetTexture.prototype.getRenderHeight = function () {
  63529. if (this._size.width) {
  63530. return this._size.height;
  63531. }
  63532. return this._size;
  63533. };
  63534. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  63535. get: function () {
  63536. return true;
  63537. },
  63538. enumerable: true,
  63539. configurable: true
  63540. });
  63541. RenderTargetTexture.prototype.scale = function (ratio) {
  63542. var newSize = this.getRenderSize() * ratio;
  63543. this.resize(newSize);
  63544. };
  63545. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  63546. if (this.isCube) {
  63547. return this._textureMatrix;
  63548. }
  63549. return _super.prototype.getReflectionTextureMatrix.call(this);
  63550. };
  63551. RenderTargetTexture.prototype.resize = function (size) {
  63552. this.releaseInternalTexture();
  63553. var scene = this.getScene();
  63554. if (!scene) {
  63555. return;
  63556. }
  63557. this._processSizeParameter(size);
  63558. if (this.isCube) {
  63559. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  63560. }
  63561. else {
  63562. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  63563. }
  63564. };
  63565. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  63566. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  63567. if (dumpForDebug === void 0) { dumpForDebug = false; }
  63568. var scene = this.getScene();
  63569. if (!scene) {
  63570. return;
  63571. }
  63572. var engine = scene.getEngine();
  63573. if (this.useCameraPostProcesses !== undefined) {
  63574. useCameraPostProcess = this.useCameraPostProcesses;
  63575. }
  63576. if (this._waitingRenderList) {
  63577. this.renderList = [];
  63578. for (var index = 0; index < this._waitingRenderList.length; index++) {
  63579. var id = this._waitingRenderList[index];
  63580. var mesh_1 = scene.getMeshByID(id);
  63581. if (mesh_1) {
  63582. this.renderList.push(mesh_1);
  63583. }
  63584. }
  63585. delete this._waitingRenderList;
  63586. }
  63587. // Is predicate defined?
  63588. if (this.renderListPredicate) {
  63589. if (this.renderList) {
  63590. this.renderList.splice(0); // Clear previous renderList
  63591. }
  63592. else {
  63593. this.renderList = [];
  63594. }
  63595. var scene = this.getScene();
  63596. if (!scene) {
  63597. return;
  63598. }
  63599. var sceneMeshes = scene.meshes;
  63600. for (var index = 0; index < sceneMeshes.length; index++) {
  63601. var mesh = sceneMeshes[index];
  63602. if (this.renderListPredicate(mesh)) {
  63603. this.renderList.push(mesh);
  63604. }
  63605. }
  63606. }
  63607. this.onBeforeBindObservable.notifyObservers(this);
  63608. // Set custom projection.
  63609. // Needs to be before binding to prevent changing the aspect ratio.
  63610. var camera;
  63611. if (this.activeCamera) {
  63612. camera = this.activeCamera;
  63613. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  63614. if (this.activeCamera !== scene.activeCamera) {
  63615. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  63616. }
  63617. }
  63618. else {
  63619. camera = scene.activeCamera;
  63620. if (camera) {
  63621. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  63622. }
  63623. }
  63624. // Prepare renderingManager
  63625. this._renderingManager.reset();
  63626. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  63627. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  63628. var sceneRenderId = scene.getRenderId();
  63629. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  63630. var mesh = currentRenderList[meshIndex];
  63631. if (mesh) {
  63632. if (!mesh.isReady(this.refreshRate === 0)) {
  63633. this.resetRefreshCounter();
  63634. continue;
  63635. }
  63636. mesh._preActivateForIntermediateRendering(sceneRenderId);
  63637. var isMasked = void 0;
  63638. if (!this.renderList && camera) {
  63639. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  63640. }
  63641. else {
  63642. isMasked = false;
  63643. }
  63644. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  63645. mesh._activate(sceneRenderId);
  63646. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  63647. var subMesh = mesh.subMeshes[subIndex];
  63648. scene._activeIndices.addCount(subMesh.indexCount, false);
  63649. this._renderingManager.dispatch(subMesh, mesh);
  63650. }
  63651. }
  63652. }
  63653. }
  63654. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  63655. var particleSystem = scene.particleSystems[particleIndex];
  63656. var emitter = particleSystem.emitter;
  63657. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  63658. continue;
  63659. }
  63660. if (currentRenderList.indexOf(emitter) >= 0) {
  63661. this._renderingManager.dispatchParticles(particleSystem);
  63662. }
  63663. }
  63664. if (this.isCube) {
  63665. for (var face = 0; face < 6; face++) {
  63666. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  63667. scene.incrementRenderId();
  63668. scene.resetCachedMaterial();
  63669. }
  63670. }
  63671. else {
  63672. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  63673. }
  63674. this.onAfterUnbindObservable.notifyObservers(this);
  63675. if (scene.activeCamera) {
  63676. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  63677. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  63678. }
  63679. engine.setViewport(scene.activeCamera.viewport);
  63680. }
  63681. scene.resetCachedMaterial();
  63682. };
  63683. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  63684. var minimum = 128;
  63685. var x = renderDimension * scale;
  63686. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  63687. // Ensure we don't exceed the render dimension (while staying POT)
  63688. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  63689. };
  63690. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  63691. var _this = this;
  63692. if (!this._texture) {
  63693. return;
  63694. }
  63695. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  63696. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  63697. });
  63698. };
  63699. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  63700. var scene = this.getScene();
  63701. if (!scene) {
  63702. return;
  63703. }
  63704. var engine = scene.getEngine();
  63705. if (!this._texture) {
  63706. return;
  63707. }
  63708. // Bind
  63709. if (this._postProcessManager) {
  63710. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  63711. }
  63712. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  63713. if (this._texture) {
  63714. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  63715. }
  63716. }
  63717. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  63718. // Clear
  63719. if (this.onClearObservable.hasObservers()) {
  63720. this.onClearObservable.notifyObservers(engine);
  63721. }
  63722. else {
  63723. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  63724. }
  63725. if (!this._doNotChangeAspectRatio) {
  63726. scene.updateTransformMatrix(true);
  63727. }
  63728. // Render
  63729. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  63730. if (this._postProcessManager) {
  63731. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  63732. }
  63733. else if (useCameraPostProcess) {
  63734. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  63735. }
  63736. if (!this._doNotChangeAspectRatio) {
  63737. scene.updateTransformMatrix(true);
  63738. }
  63739. // Dump ?
  63740. if (dumpForDebug) {
  63741. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  63742. }
  63743. // Unbind
  63744. if (!this.isCube || faceIndex === 5) {
  63745. if (this.isCube) {
  63746. if (faceIndex === 5) {
  63747. engine.generateMipMapsForCubemap(this._texture);
  63748. }
  63749. }
  63750. this.unbindFrameBuffer(engine, faceIndex);
  63751. }
  63752. else {
  63753. this.onAfterRenderObservable.notifyObservers(faceIndex);
  63754. }
  63755. };
  63756. /**
  63757. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  63758. * This allowed control for front to back rendering or reversly depending of the special needs.
  63759. *
  63760. * @param renderingGroupId The rendering group id corresponding to its index
  63761. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  63762. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  63763. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  63764. */
  63765. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  63766. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  63767. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  63768. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  63769. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  63770. };
  63771. /**
  63772. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  63773. *
  63774. * @param renderingGroupId The rendering group id corresponding to its index
  63775. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  63776. */
  63777. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  63778. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  63779. };
  63780. RenderTargetTexture.prototype.clone = function () {
  63781. var textureSize = this.getSize();
  63782. 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);
  63783. // Base texture
  63784. newTexture.hasAlpha = this.hasAlpha;
  63785. newTexture.level = this.level;
  63786. // RenderTarget Texture
  63787. newTexture.coordinatesMode = this.coordinatesMode;
  63788. if (this.renderList) {
  63789. newTexture.renderList = this.renderList.slice(0);
  63790. }
  63791. return newTexture;
  63792. };
  63793. RenderTargetTexture.prototype.serialize = function () {
  63794. if (!this.name) {
  63795. return null;
  63796. }
  63797. var serializationObject = _super.prototype.serialize.call(this);
  63798. serializationObject.renderTargetSize = this.getRenderSize();
  63799. serializationObject.renderList = [];
  63800. if (this.renderList) {
  63801. for (var index = 0; index < this.renderList.length; index++) {
  63802. serializationObject.renderList.push(this.renderList[index].id);
  63803. }
  63804. }
  63805. return serializationObject;
  63806. };
  63807. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  63808. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  63809. var objBuffer = this.getInternalTexture();
  63810. var scene = this.getScene();
  63811. if (objBuffer && scene) {
  63812. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  63813. }
  63814. };
  63815. RenderTargetTexture.prototype.dispose = function () {
  63816. if (this._postProcessManager) {
  63817. this._postProcessManager.dispose();
  63818. this._postProcessManager = null;
  63819. }
  63820. this.clearPostProcesses(true);
  63821. if (this._resizeObserver) {
  63822. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  63823. this._resizeObserver = null;
  63824. }
  63825. this.renderList = null;
  63826. // Remove from custom render targets
  63827. var scene = this.getScene();
  63828. if (!scene) {
  63829. return;
  63830. }
  63831. var index = scene.customRenderTargets.indexOf(this);
  63832. if (index >= 0) {
  63833. scene.customRenderTargets.splice(index, 1);
  63834. }
  63835. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  63836. var camera = _a[_i];
  63837. index = camera.customRenderTargets.indexOf(this);
  63838. if (index >= 0) {
  63839. camera.customRenderTargets.splice(index, 1);
  63840. }
  63841. }
  63842. _super.prototype.dispose.call(this);
  63843. };
  63844. RenderTargetTexture.prototype._rebuild = function () {
  63845. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  63846. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  63847. }
  63848. if (this._postProcessManager) {
  63849. this._postProcessManager._rebuild();
  63850. }
  63851. };
  63852. /**
  63853. * Clear the info related to rendering groups preventing retention point in material dispose.
  63854. */
  63855. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  63856. if (this._renderingManager) {
  63857. this._renderingManager.freeRenderingGroups();
  63858. }
  63859. };
  63860. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  63861. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  63862. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  63863. return RenderTargetTexture;
  63864. }(BABYLON.Texture));
  63865. BABYLON.RenderTargetTexture = RenderTargetTexture;
  63866. })(BABYLON || (BABYLON = {}));
  63867. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  63868. var BABYLON;
  63869. (function (BABYLON) {
  63870. ;
  63871. var MultiRenderTarget = /** @class */ (function (_super) {
  63872. __extends(MultiRenderTarget, _super);
  63873. function MultiRenderTarget(name, size, count, scene, options) {
  63874. var _this = this;
  63875. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  63876. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  63877. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  63878. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  63879. _this._engine = scene.getEngine();
  63880. if (!_this.isSupported) {
  63881. _this.dispose();
  63882. return;
  63883. }
  63884. var types = [];
  63885. var samplingModes = [];
  63886. for (var i = 0; i < count; i++) {
  63887. if (options && options.types && options.types[i] !== undefined) {
  63888. types.push(options.types[i]);
  63889. }
  63890. else {
  63891. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  63892. }
  63893. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  63894. samplingModes.push(options.samplingModes[i]);
  63895. }
  63896. else {
  63897. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  63898. }
  63899. }
  63900. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  63901. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  63902. _this._size = size;
  63903. _this._multiRenderTargetOptions = {
  63904. samplingModes: samplingModes,
  63905. generateMipMaps: generateMipMaps,
  63906. generateDepthBuffer: generateDepthBuffer,
  63907. generateStencilBuffer: generateStencilBuffer,
  63908. generateDepthTexture: generateDepthTexture,
  63909. types: types,
  63910. textureCount: count
  63911. };
  63912. _this._createInternalTextures();
  63913. _this._createTextures();
  63914. return _this;
  63915. }
  63916. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  63917. get: function () {
  63918. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  63919. },
  63920. enumerable: true,
  63921. configurable: true
  63922. });
  63923. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  63924. get: function () {
  63925. return this._textures;
  63926. },
  63927. enumerable: true,
  63928. configurable: true
  63929. });
  63930. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  63931. get: function () {
  63932. return this._textures[this._textures.length - 1];
  63933. },
  63934. enumerable: true,
  63935. configurable: true
  63936. });
  63937. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  63938. set: function (wrap) {
  63939. if (this._textures) {
  63940. for (var i = 0; i < this._textures.length; i++) {
  63941. this._textures[i].wrapU = wrap;
  63942. }
  63943. }
  63944. },
  63945. enumerable: true,
  63946. configurable: true
  63947. });
  63948. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  63949. set: function (wrap) {
  63950. if (this._textures) {
  63951. for (var i = 0; i < this._textures.length; i++) {
  63952. this._textures[i].wrapV = wrap;
  63953. }
  63954. }
  63955. },
  63956. enumerable: true,
  63957. configurable: true
  63958. });
  63959. MultiRenderTarget.prototype._rebuild = function () {
  63960. this.releaseInternalTextures();
  63961. this._createInternalTextures();
  63962. for (var i = 0; i < this._internalTextures.length; i++) {
  63963. var texture = this._textures[i];
  63964. texture._texture = this._internalTextures[i];
  63965. }
  63966. // Keeps references to frame buffer and stencil/depth buffer
  63967. this._texture = this._internalTextures[0];
  63968. };
  63969. MultiRenderTarget.prototype._createInternalTextures = function () {
  63970. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  63971. };
  63972. MultiRenderTarget.prototype._createTextures = function () {
  63973. this._textures = [];
  63974. for (var i = 0; i < this._internalTextures.length; i++) {
  63975. var texture = new BABYLON.Texture(null, this.getScene());
  63976. texture._texture = this._internalTextures[i];
  63977. this._textures.push(texture);
  63978. }
  63979. // Keeps references to frame buffer and stencil/depth buffer
  63980. this._texture = this._internalTextures[0];
  63981. };
  63982. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  63983. get: function () {
  63984. return this._samples;
  63985. },
  63986. set: function (value) {
  63987. if (this._samples === value) {
  63988. return;
  63989. }
  63990. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  63991. },
  63992. enumerable: true,
  63993. configurable: true
  63994. });
  63995. MultiRenderTarget.prototype.resize = function (size) {
  63996. this.releaseInternalTextures();
  63997. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  63998. this._createInternalTextures();
  63999. };
  64000. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  64001. var _this = this;
  64002. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  64003. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  64004. });
  64005. };
  64006. MultiRenderTarget.prototype.dispose = function () {
  64007. this.releaseInternalTextures();
  64008. _super.prototype.dispose.call(this);
  64009. };
  64010. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  64011. if (!this._internalTextures) {
  64012. return;
  64013. }
  64014. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  64015. if (this._internalTextures[i] !== undefined) {
  64016. this._internalTextures[i].dispose();
  64017. this._internalTextures.splice(i, 1);
  64018. }
  64019. }
  64020. };
  64021. return MultiRenderTarget;
  64022. }(BABYLON.RenderTargetTexture));
  64023. BABYLON.MultiRenderTarget = MultiRenderTarget;
  64024. })(BABYLON || (BABYLON = {}));
  64025. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  64026. var BABYLON;
  64027. (function (BABYLON) {
  64028. var MirrorTexture = /** @class */ (function (_super) {
  64029. __extends(MirrorTexture, _super);
  64030. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  64031. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64032. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  64033. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  64034. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  64035. _this.scene = scene;
  64036. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  64037. _this._transformMatrix = BABYLON.Matrix.Zero();
  64038. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  64039. _this._adaptiveBlurKernel = 0;
  64040. _this._blurKernelX = 0;
  64041. _this._blurKernelY = 0;
  64042. _this._blurRatio = 1.0;
  64043. _this.ignoreCameraViewport = true;
  64044. _this._updateGammaSpace();
  64045. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  64046. _this._updateGammaSpace;
  64047. });
  64048. _this.onBeforeRenderObservable.add(function () {
  64049. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  64050. _this._savedViewMatrix = scene.getViewMatrix();
  64051. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  64052. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  64053. scene.clipPlane = _this.mirrorPlane;
  64054. scene.getEngine().cullBackFaces = false;
  64055. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  64056. });
  64057. _this.onAfterRenderObservable.add(function () {
  64058. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  64059. scene.getEngine().cullBackFaces = true;
  64060. scene._mirroredCameraPosition = null;
  64061. delete scene.clipPlane;
  64062. });
  64063. return _this;
  64064. }
  64065. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  64066. get: function () {
  64067. return this._blurRatio;
  64068. },
  64069. set: function (value) {
  64070. if (this._blurRatio === value) {
  64071. return;
  64072. }
  64073. this._blurRatio = value;
  64074. this._preparePostProcesses();
  64075. },
  64076. enumerable: true,
  64077. configurable: true
  64078. });
  64079. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  64080. set: function (value) {
  64081. this._adaptiveBlurKernel = value;
  64082. this._autoComputeBlurKernel();
  64083. },
  64084. enumerable: true,
  64085. configurable: true
  64086. });
  64087. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  64088. set: function (value) {
  64089. this.blurKernelX = value;
  64090. this.blurKernelY = value;
  64091. },
  64092. enumerable: true,
  64093. configurable: true
  64094. });
  64095. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  64096. get: function () {
  64097. return this._blurKernelX;
  64098. },
  64099. set: function (value) {
  64100. if (this._blurKernelX === value) {
  64101. return;
  64102. }
  64103. this._blurKernelX = value;
  64104. this._preparePostProcesses();
  64105. },
  64106. enumerable: true,
  64107. configurable: true
  64108. });
  64109. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  64110. get: function () {
  64111. return this._blurKernelY;
  64112. },
  64113. set: function (value) {
  64114. if (this._blurKernelY === value) {
  64115. return;
  64116. }
  64117. this._blurKernelY = value;
  64118. this._preparePostProcesses();
  64119. },
  64120. enumerable: true,
  64121. configurable: true
  64122. });
  64123. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  64124. var engine = this.getScene().getEngine();
  64125. var dw = this.getRenderWidth() / engine.getRenderWidth();
  64126. var dh = this.getRenderHeight() / engine.getRenderHeight();
  64127. this.blurKernelX = this._adaptiveBlurKernel * dw;
  64128. this.blurKernelY = this._adaptiveBlurKernel * dh;
  64129. };
  64130. MirrorTexture.prototype._onRatioRescale = function () {
  64131. if (this._sizeRatio) {
  64132. this.resize(this._initialSizeParameter);
  64133. if (!this._adaptiveBlurKernel) {
  64134. this._preparePostProcesses();
  64135. }
  64136. }
  64137. if (this._adaptiveBlurKernel) {
  64138. this._autoComputeBlurKernel();
  64139. }
  64140. };
  64141. MirrorTexture.prototype._updateGammaSpace = function () {
  64142. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  64143. };
  64144. MirrorTexture.prototype._preparePostProcesses = function () {
  64145. this.clearPostProcesses(true);
  64146. if (this._blurKernelX && this._blurKernelY) {
  64147. var engine = this.getScene().getEngine();
  64148. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  64149. 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);
  64150. this._blurX.autoClear = false;
  64151. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  64152. this._blurX.inputTexture = this._texture;
  64153. }
  64154. else {
  64155. this._blurX.alwaysForcePOT = true;
  64156. }
  64157. 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);
  64158. this._blurY.autoClear = false;
  64159. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  64160. this.addPostProcess(this._blurX);
  64161. this.addPostProcess(this._blurY);
  64162. }
  64163. else {
  64164. if (this._blurY) {
  64165. this.removePostProcess(this._blurY);
  64166. this._blurY.dispose();
  64167. this._blurY = null;
  64168. }
  64169. if (this._blurX) {
  64170. this.removePostProcess(this._blurX);
  64171. this._blurX.dispose();
  64172. this._blurX = null;
  64173. }
  64174. }
  64175. };
  64176. MirrorTexture.prototype.clone = function () {
  64177. var scene = this.getScene();
  64178. if (!scene) {
  64179. return this;
  64180. }
  64181. var textureSize = this.getSize();
  64182. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  64183. // Base texture
  64184. newTexture.hasAlpha = this.hasAlpha;
  64185. newTexture.level = this.level;
  64186. // Mirror Texture
  64187. newTexture.mirrorPlane = this.mirrorPlane.clone();
  64188. if (this.renderList) {
  64189. newTexture.renderList = this.renderList.slice(0);
  64190. }
  64191. return newTexture;
  64192. };
  64193. MirrorTexture.prototype.serialize = function () {
  64194. if (!this.name) {
  64195. return null;
  64196. }
  64197. var serializationObject = _super.prototype.serialize.call(this);
  64198. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  64199. return serializationObject;
  64200. };
  64201. MirrorTexture.prototype.dispose = function () {
  64202. _super.prototype.dispose.call(this);
  64203. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  64204. };
  64205. return MirrorTexture;
  64206. }(BABYLON.RenderTargetTexture));
  64207. BABYLON.MirrorTexture = MirrorTexture;
  64208. })(BABYLON || (BABYLON = {}));
  64209. //# sourceMappingURL=babylon.mirrorTexture.js.map
  64210. var BABYLON;
  64211. (function (BABYLON) {
  64212. /**
  64213. * Creates a refraction texture used by refraction channel of the standard material.
  64214. * @param name the texture name
  64215. * @param size size of the underlying texture
  64216. * @param scene root scene
  64217. */
  64218. var RefractionTexture = /** @class */ (function (_super) {
  64219. __extends(RefractionTexture, _super);
  64220. function RefractionTexture(name, size, scene, generateMipMaps) {
  64221. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  64222. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  64223. _this.depth = 2.0;
  64224. _this.onBeforeRenderObservable.add(function () {
  64225. scene.clipPlane = _this.refractionPlane;
  64226. });
  64227. _this.onAfterRenderObservable.add(function () {
  64228. delete scene.clipPlane;
  64229. });
  64230. return _this;
  64231. }
  64232. RefractionTexture.prototype.clone = function () {
  64233. var scene = this.getScene();
  64234. if (!scene) {
  64235. return this;
  64236. }
  64237. var textureSize = this.getSize();
  64238. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  64239. // Base texture
  64240. newTexture.hasAlpha = this.hasAlpha;
  64241. newTexture.level = this.level;
  64242. // Refraction Texture
  64243. newTexture.refractionPlane = this.refractionPlane.clone();
  64244. if (this.renderList) {
  64245. newTexture.renderList = this.renderList.slice(0);
  64246. }
  64247. newTexture.depth = this.depth;
  64248. return newTexture;
  64249. };
  64250. RefractionTexture.prototype.serialize = function () {
  64251. if (!this.name) {
  64252. return null;
  64253. }
  64254. var serializationObject = _super.prototype.serialize.call(this);
  64255. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  64256. serializationObject.depth = this.depth;
  64257. return serializationObject;
  64258. };
  64259. return RefractionTexture;
  64260. }(BABYLON.RenderTargetTexture));
  64261. BABYLON.RefractionTexture = RefractionTexture;
  64262. })(BABYLON || (BABYLON = {}));
  64263. //# sourceMappingURL=babylon.refractionTexture.js.map
  64264. var BABYLON;
  64265. (function (BABYLON) {
  64266. /**
  64267. * A class extending {BABYLON.Texture} allowing drawing on a texture
  64268. * @see http://doc.babylonjs.com/how_to/dynamictexture
  64269. */
  64270. var DynamicTexture = /** @class */ (function (_super) {
  64271. __extends(DynamicTexture, _super);
  64272. /**
  64273. * Creates a {BABYLON.DynamicTexture}
  64274. * @param name defines the name of the texture
  64275. * @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
  64276. * @param scene defines the scene where you want the texture
  64277. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  64278. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  64279. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  64280. */
  64281. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  64282. if (scene === void 0) { scene = null; }
  64283. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64284. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  64285. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  64286. _this.name = name;
  64287. _this._engine = _this.getScene().getEngine();
  64288. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64289. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64290. _this._generateMipMaps = generateMipMaps;
  64291. if (options.getContext) {
  64292. _this._canvas = options;
  64293. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64294. }
  64295. else {
  64296. _this._canvas = document.createElement("canvas");
  64297. if (options.width || options.width === 0) {
  64298. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64299. }
  64300. else {
  64301. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  64302. }
  64303. }
  64304. var textureSize = _this.getSize();
  64305. _this._canvas.width = textureSize.width;
  64306. _this._canvas.height = textureSize.height;
  64307. _this._context = _this._canvas.getContext("2d");
  64308. return _this;
  64309. }
  64310. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  64311. /**
  64312. * Gets the current state of canRescale
  64313. */
  64314. get: function () {
  64315. return true;
  64316. },
  64317. enumerable: true,
  64318. configurable: true
  64319. });
  64320. DynamicTexture.prototype._recreate = function (textureSize) {
  64321. this._canvas.width = textureSize.width;
  64322. this._canvas.height = textureSize.height;
  64323. this.releaseInternalTexture();
  64324. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  64325. };
  64326. /**
  64327. * Scales the texture
  64328. * @param ratio the scale factor to apply to both width and height
  64329. */
  64330. DynamicTexture.prototype.scale = function (ratio) {
  64331. var textureSize = this.getSize();
  64332. textureSize.width *= ratio;
  64333. textureSize.height *= ratio;
  64334. this._recreate(textureSize);
  64335. };
  64336. /**
  64337. * Resizes the texture
  64338. * @param width the new width
  64339. * @param height the new height
  64340. */
  64341. DynamicTexture.prototype.scaleTo = function (width, height) {
  64342. var textureSize = this.getSize();
  64343. textureSize.width = width;
  64344. textureSize.height = height;
  64345. this._recreate(textureSize);
  64346. };
  64347. /**
  64348. * Gets the context of the canvas used by the texture
  64349. * @returns the canvas context of the dynamic texture
  64350. */
  64351. DynamicTexture.prototype.getContext = function () {
  64352. return this._context;
  64353. };
  64354. /**
  64355. * Clears the texture
  64356. */
  64357. DynamicTexture.prototype.clear = function () {
  64358. var size = this.getSize();
  64359. this._context.fillRect(0, 0, size.width, size.height);
  64360. };
  64361. /**
  64362. * Updates the texture
  64363. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64364. */
  64365. DynamicTexture.prototype.update = function (invertY) {
  64366. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  64367. };
  64368. /**
  64369. * Draws text onto the texture
  64370. * @param text defines the text to be drawn
  64371. * @param x defines the placement of the text from the left
  64372. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  64373. * @param font defines the font to be used with font-style, font-size, font-name
  64374. * @param color defines the color used for the text
  64375. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  64376. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64377. * @param update defines whether texture is immediately update (default is true)
  64378. */
  64379. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  64380. if (update === void 0) { update = true; }
  64381. var size = this.getSize();
  64382. if (clearColor) {
  64383. this._context.fillStyle = clearColor;
  64384. this._context.fillRect(0, 0, size.width, size.height);
  64385. }
  64386. this._context.font = font;
  64387. if (x === null || x === undefined) {
  64388. var textSize = this._context.measureText(text);
  64389. x = (size.width - textSize.width) / 2;
  64390. }
  64391. if (y === null || y === undefined) {
  64392. var fontSize = parseInt((font.replace(/\D/g, '')));
  64393. y = (size.height / 2) + (fontSize / 3.65);
  64394. }
  64395. this._context.fillStyle = color;
  64396. this._context.fillText(text, x, y);
  64397. if (update) {
  64398. this.update(invertY);
  64399. }
  64400. };
  64401. /**
  64402. * Clones the texture
  64403. * @returns the clone of the texture.
  64404. */
  64405. DynamicTexture.prototype.clone = function () {
  64406. var scene = this.getScene();
  64407. if (!scene) {
  64408. return this;
  64409. }
  64410. var textureSize = this.getSize();
  64411. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  64412. // Base texture
  64413. newTexture.hasAlpha = this.hasAlpha;
  64414. newTexture.level = this.level;
  64415. // Dynamic Texture
  64416. newTexture.wrapU = this.wrapU;
  64417. newTexture.wrapV = this.wrapV;
  64418. return newTexture;
  64419. };
  64420. /** @hidden */
  64421. DynamicTexture.prototype._rebuild = function () {
  64422. this.update();
  64423. };
  64424. return DynamicTexture;
  64425. }(BABYLON.Texture));
  64426. BABYLON.DynamicTexture = DynamicTexture;
  64427. })(BABYLON || (BABYLON = {}));
  64428. //# sourceMappingURL=babylon.dynamicTexture.js.map
  64429. var BABYLON;
  64430. (function (BABYLON) {
  64431. var VideoTexture = /** @class */ (function (_super) {
  64432. __extends(VideoTexture, _super);
  64433. /**
  64434. * Creates a video texture.
  64435. * Sample : https://doc.babylonjs.com/how_to/video_texture
  64436. * @param {string | null} name optional name, will detect from video source, if not defined
  64437. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  64438. * @param {BABYLON.Scene} scene is obviously the current scene.
  64439. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  64440. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  64441. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  64442. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  64443. */
  64444. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  64445. if (generateMipMaps === void 0) { generateMipMaps = false; }
  64446. if (invertY === void 0) { invertY = false; }
  64447. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64448. if (settings === void 0) { settings = {
  64449. autoPlay: true,
  64450. loop: true,
  64451. autoUpdateTexture: true,
  64452. }; }
  64453. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64454. _this._stillImageCaptured = false;
  64455. _this._createInternalTexture = function () {
  64456. if (_this._texture != null) {
  64457. return;
  64458. }
  64459. if (!_this._engine.needPOTTextures ||
  64460. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  64461. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  64462. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  64463. }
  64464. else {
  64465. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64466. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64467. _this._generateMipMaps = false;
  64468. }
  64469. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  64470. if (!_this.video.autoplay) {
  64471. var oldHandler_1 = _this.video.onplaying;
  64472. _this.video.onplaying = function () {
  64473. _this.video.onplaying = oldHandler_1;
  64474. _this._texture.isReady = true;
  64475. _this._updateInternalTexture();
  64476. _this.video.pause();
  64477. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64478. _this.onLoadObservable.notifyObservers(_this);
  64479. }
  64480. };
  64481. _this.video.play();
  64482. }
  64483. else {
  64484. _this._texture.isReady = true;
  64485. _this._updateInternalTexture();
  64486. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64487. _this.onLoadObservable.notifyObservers(_this);
  64488. }
  64489. }
  64490. };
  64491. _this.reset = function () {
  64492. if (_this._texture == null) {
  64493. return;
  64494. }
  64495. _this._texture.dispose();
  64496. _this._texture = null;
  64497. };
  64498. _this._updateInternalTexture = function (e) {
  64499. if (_this._texture == null || !_this._texture.isReady) {
  64500. return;
  64501. }
  64502. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  64503. return;
  64504. }
  64505. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  64506. };
  64507. _this._engine = _this.getScene().getEngine();
  64508. _this._generateMipMaps = generateMipMaps;
  64509. _this._samplingMode = samplingMode;
  64510. _this.autoUpdateTexture = settings.autoUpdateTexture;
  64511. _this.name = name || _this._getName(src);
  64512. _this.video = _this._getVideo(src);
  64513. if (settings.autoPlay !== undefined) {
  64514. _this.video.autoplay = settings.autoPlay;
  64515. }
  64516. if (settings.loop !== undefined) {
  64517. _this.video.loop = settings.loop;
  64518. }
  64519. _this.video.addEventListener("canplay", _this._createInternalTexture);
  64520. _this.video.addEventListener("paused", _this._updateInternalTexture);
  64521. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  64522. _this.video.addEventListener("emptied", _this.reset);
  64523. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  64524. _this._createInternalTexture();
  64525. }
  64526. return _this;
  64527. }
  64528. VideoTexture.prototype._getName = function (src) {
  64529. if (src instanceof HTMLVideoElement) {
  64530. return src.currentSrc;
  64531. }
  64532. if (typeof src === "object") {
  64533. return src.toString();
  64534. }
  64535. return src;
  64536. };
  64537. ;
  64538. VideoTexture.prototype._getVideo = function (src) {
  64539. if (src instanceof HTMLVideoElement) {
  64540. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  64541. return src;
  64542. }
  64543. var video = document.createElement("video");
  64544. if (typeof src === "string") {
  64545. BABYLON.Tools.SetCorsBehavior(src, video);
  64546. video.src = src;
  64547. }
  64548. else {
  64549. BABYLON.Tools.SetCorsBehavior(src[0], video);
  64550. src.forEach(function (url) {
  64551. var source = document.createElement("source");
  64552. source.src = url;
  64553. video.appendChild(source);
  64554. });
  64555. }
  64556. return video;
  64557. };
  64558. ;
  64559. /**
  64560. * Internal method to initiate `update`.
  64561. */
  64562. VideoTexture.prototype._rebuild = function () {
  64563. this.update();
  64564. };
  64565. /**
  64566. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  64567. */
  64568. VideoTexture.prototype.update = function () {
  64569. if (!this.autoUpdateTexture) {
  64570. // Expecting user to call `updateTexture` manually
  64571. return;
  64572. }
  64573. this.updateTexture(true);
  64574. };
  64575. /**
  64576. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  64577. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  64578. */
  64579. VideoTexture.prototype.updateTexture = function (isVisible) {
  64580. if (!isVisible) {
  64581. return;
  64582. }
  64583. if (this.video.paused && this._stillImageCaptured) {
  64584. return;
  64585. }
  64586. this._stillImageCaptured = true;
  64587. this._updateInternalTexture();
  64588. };
  64589. /**
  64590. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  64591. * @param url New url.
  64592. */
  64593. VideoTexture.prototype.updateURL = function (url) {
  64594. this.video.src = url;
  64595. };
  64596. VideoTexture.prototype.dispose = function () {
  64597. _super.prototype.dispose.call(this);
  64598. this.video.removeEventListener("canplay", this._createInternalTexture);
  64599. this.video.removeEventListener("paused", this._updateInternalTexture);
  64600. this.video.removeEventListener("seeked", this._updateInternalTexture);
  64601. this.video.removeEventListener("emptied", this.reset);
  64602. this.video.pause();
  64603. };
  64604. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  64605. var video = document.createElement("video");
  64606. var constraintsDeviceId;
  64607. if (constraints && constraints.deviceId) {
  64608. constraintsDeviceId = {
  64609. exact: constraints.deviceId,
  64610. };
  64611. }
  64612. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  64613. if (navigator.mediaDevices) {
  64614. navigator.mediaDevices.getUserMedia({ video: constraints })
  64615. .then(function (stream) {
  64616. if (video.mozSrcObject !== undefined) {
  64617. // hack for Firefox < 19
  64618. video.mozSrcObject = stream;
  64619. }
  64620. else {
  64621. video.srcObject = stream;
  64622. }
  64623. var onPlaying = function () {
  64624. if (onReady) {
  64625. onReady(new VideoTexture("video", video, scene, true, true));
  64626. }
  64627. video.removeEventListener("playing", onPlaying);
  64628. };
  64629. video.addEventListener("playing", onPlaying);
  64630. video.play();
  64631. })
  64632. .catch(function (err) {
  64633. BABYLON.Tools.Error(err.name);
  64634. });
  64635. }
  64636. else {
  64637. navigator.getUserMedia =
  64638. navigator.getUserMedia ||
  64639. navigator.webkitGetUserMedia ||
  64640. navigator.mozGetUserMedia ||
  64641. navigator.msGetUserMedia;
  64642. if (navigator.getUserMedia) {
  64643. navigator.getUserMedia({
  64644. video: {
  64645. deviceId: constraintsDeviceId,
  64646. width: {
  64647. min: (constraints && constraints.minWidth) || 256,
  64648. max: (constraints && constraints.maxWidth) || 640,
  64649. },
  64650. height: {
  64651. min: (constraints && constraints.minHeight) || 256,
  64652. max: (constraints && constraints.maxHeight) || 480,
  64653. },
  64654. },
  64655. }, function (stream) {
  64656. if (video.mozSrcObject !== undefined) {
  64657. // hack for Firefox < 19
  64658. video.mozSrcObject = stream;
  64659. }
  64660. else {
  64661. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  64662. }
  64663. video.play();
  64664. if (onReady) {
  64665. onReady(new VideoTexture("video", video, scene, true, true));
  64666. }
  64667. }, function (e) {
  64668. BABYLON.Tools.Error(e.name);
  64669. });
  64670. }
  64671. }
  64672. };
  64673. return VideoTexture;
  64674. }(BABYLON.Texture));
  64675. BABYLON.VideoTexture = VideoTexture;
  64676. })(BABYLON || (BABYLON = {}));
  64677. //# sourceMappingURL=babylon.videoTexture.js.map
  64678. var BABYLON;
  64679. (function (BABYLON) {
  64680. var RawTexture = /** @class */ (function (_super) {
  64681. __extends(RawTexture, _super);
  64682. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  64683. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64684. if (invertY === void 0) { invertY = false; }
  64685. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64686. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64687. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64688. _this.format = format;
  64689. _this._engine = scene.getEngine();
  64690. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  64691. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64692. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64693. return _this;
  64694. }
  64695. RawTexture.prototype.update = function (data) {
  64696. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  64697. };
  64698. // Statics
  64699. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64700. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64701. if (invertY === void 0) { invertY = false; }
  64702. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64703. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  64704. };
  64705. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64706. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64707. if (invertY === void 0) { invertY = false; }
  64708. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64709. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  64710. };
  64711. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64712. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64713. if (invertY === void 0) { invertY = false; }
  64714. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64715. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  64716. };
  64717. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  64718. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64719. if (invertY === void 0) { invertY = false; }
  64720. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64721. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64722. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  64723. };
  64724. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  64725. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64726. if (invertY === void 0) { invertY = false; }
  64727. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64728. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64729. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  64730. };
  64731. return RawTexture;
  64732. }(BABYLON.Texture));
  64733. BABYLON.RawTexture = RawTexture;
  64734. })(BABYLON || (BABYLON = {}));
  64735. //# sourceMappingURL=babylon.rawTexture.js.map
  64736. var BABYLON;
  64737. (function (BABYLON) {
  64738. /**
  64739. * Class used to store 3D textures containing user data
  64740. */
  64741. var RawTexture3D = /** @class */ (function (_super) {
  64742. __extends(RawTexture3D, _super);
  64743. /**
  64744. * Create a new RawTexture3D
  64745. * @param data defines the data of the texture
  64746. * @param width defines the width of the texture
  64747. * @param height defines the height of the texture
  64748. * @param depth defines the depth of the texture
  64749. * @param format defines the texture format to use
  64750. * @param scene defines the hosting scene
  64751. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  64752. * @param invertY defines if texture must be stored with Y axis inverted
  64753. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  64754. */
  64755. function RawTexture3D(data, width, height, depth,
  64756. /** Gets or sets the texture format to use*/
  64757. format, scene, generateMipMaps, invertY, samplingMode) {
  64758. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64759. if (invertY === void 0) { invertY = false; }
  64760. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64761. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64762. _this.format = format;
  64763. _this._engine = scene.getEngine();
  64764. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode);
  64765. _this.is3D = true;
  64766. return _this;
  64767. }
  64768. /**
  64769. * Update the texture with new data
  64770. * @param data defines the data to store in the texture
  64771. */
  64772. RawTexture3D.prototype.update = function (data) {
  64773. if (!this._texture) {
  64774. return;
  64775. }
  64776. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY);
  64777. };
  64778. return RawTexture3D;
  64779. }(BABYLON.Texture));
  64780. BABYLON.RawTexture3D = RawTexture3D;
  64781. })(BABYLON || (BABYLON = {}));
  64782. //# sourceMappingURL=babylon.rawTexture3D.js.map
  64783. var BABYLON;
  64784. (function (BABYLON) {
  64785. /**
  64786. * PostProcess can be used to apply a shader to a texture after it has been rendered
  64787. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  64788. */
  64789. var PostProcess = /** @class */ (function () {
  64790. /**
  64791. * Creates a new instance PostProcess
  64792. * @param name The name of the PostProcess.
  64793. * @param fragmentUrl The url of the fragment shader to be used.
  64794. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  64795. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  64796. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  64797. * @param camera The camera to apply the render pass to.
  64798. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  64799. * @param engine The engine which the post process will be applied. (default: current engine)
  64800. * @param reusable If the post process can be reused on the same frame. (default: false)
  64801. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  64802. * @param textureType Type of textures used when performing the post process. (default: 0)
  64803. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  64804. * @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
  64805. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  64806. */
  64807. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  64808. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  64809. if (defines === void 0) { defines = null; }
  64810. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64811. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  64812. if (blockCompilation === void 0) { blockCompilation = false; }
  64813. this.name = name;
  64814. /**
  64815. * Width of the texture to apply the post process on
  64816. */
  64817. this.width = -1;
  64818. /**
  64819. * Height of the texture to apply the post process on
  64820. */
  64821. this.height = -1;
  64822. /**
  64823. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  64824. */
  64825. this._outputTexture = null;
  64826. /**
  64827. * If the buffer needs to be cleared before applying the post process. (default: true)
  64828. * Should be set to false if shader will overwrite all previous pixels.
  64829. */
  64830. this.autoClear = true;
  64831. /**
  64832. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  64833. */
  64834. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  64835. /**
  64836. * Animations to be used for the post processing
  64837. */
  64838. this.animations = new Array();
  64839. /**
  64840. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  64841. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  64842. */
  64843. this.enablePixelPerfectMode = false;
  64844. /**
  64845. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  64846. */
  64847. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  64848. /**
  64849. * Force textures to be a power of two (default: false)
  64850. */
  64851. this.alwaysForcePOT = false;
  64852. /**
  64853. * Number of sample textures (default: 1)
  64854. */
  64855. this.samples = 1;
  64856. /**
  64857. * Modify the scale of the post process to be the same as the viewport (default: false)
  64858. */
  64859. this.adaptScaleToCurrentViewport = false;
  64860. this._reusable = false;
  64861. /**
  64862. * Smart array of input and output textures for the post process.
  64863. */
  64864. this._textures = new BABYLON.SmartArray(2);
  64865. /**
  64866. * The index in _textures that corresponds to the output texture.
  64867. */
  64868. this._currentRenderTextureInd = 0;
  64869. this._scaleRatio = new BABYLON.Vector2(1, 1);
  64870. this._texelSize = BABYLON.Vector2.Zero();
  64871. // Events
  64872. /**
  64873. * An event triggered when the postprocess is activated.
  64874. */
  64875. this.onActivateObservable = new BABYLON.Observable();
  64876. /**
  64877. * An event triggered when the postprocess changes its size.
  64878. */
  64879. this.onSizeChangedObservable = new BABYLON.Observable();
  64880. /**
  64881. * An event triggered when the postprocess applies its effect.
  64882. */
  64883. this.onApplyObservable = new BABYLON.Observable();
  64884. /**
  64885. * An event triggered before rendering the postprocess
  64886. */
  64887. this.onBeforeRenderObservable = new BABYLON.Observable();
  64888. /**
  64889. * An event triggered after rendering the postprocess
  64890. */
  64891. this.onAfterRenderObservable = new BABYLON.Observable();
  64892. if (camera != null) {
  64893. this._camera = camera;
  64894. this._scene = camera.getScene();
  64895. camera.attachPostProcess(this);
  64896. this._engine = this._scene.getEngine();
  64897. this._scene.postProcesses.push(this);
  64898. }
  64899. else if (engine) {
  64900. this._engine = engine;
  64901. this._engine.postProcesses.push(this);
  64902. }
  64903. this._options = options;
  64904. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  64905. this._reusable = reusable || false;
  64906. this._textureType = textureType;
  64907. this._samplers = samplers || [];
  64908. this._samplers.push("textureSampler");
  64909. this._fragmentUrl = fragmentUrl;
  64910. this._vertexUrl = vertexUrl;
  64911. this._parameters = parameters || [];
  64912. this._parameters.push("scale");
  64913. this._indexParameters = indexParameters;
  64914. if (!blockCompilation) {
  64915. this.updateEffect(defines);
  64916. }
  64917. }
  64918. Object.defineProperty(PostProcess.prototype, "onActivate", {
  64919. /**
  64920. * A function that is added to the onActivateObservable
  64921. */
  64922. set: function (callback) {
  64923. if (this._onActivateObserver) {
  64924. this.onActivateObservable.remove(this._onActivateObserver);
  64925. }
  64926. if (callback) {
  64927. this._onActivateObserver = this.onActivateObservable.add(callback);
  64928. }
  64929. },
  64930. enumerable: true,
  64931. configurable: true
  64932. });
  64933. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  64934. /**
  64935. * A function that is added to the onSizeChangedObservable
  64936. */
  64937. set: function (callback) {
  64938. if (this._onSizeChangedObserver) {
  64939. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  64940. }
  64941. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  64942. },
  64943. enumerable: true,
  64944. configurable: true
  64945. });
  64946. Object.defineProperty(PostProcess.prototype, "onApply", {
  64947. /**
  64948. * A function that is added to the onApplyObservable
  64949. */
  64950. set: function (callback) {
  64951. if (this._onApplyObserver) {
  64952. this.onApplyObservable.remove(this._onApplyObserver);
  64953. }
  64954. this._onApplyObserver = this.onApplyObservable.add(callback);
  64955. },
  64956. enumerable: true,
  64957. configurable: true
  64958. });
  64959. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  64960. /**
  64961. * A function that is added to the onBeforeRenderObservable
  64962. */
  64963. set: function (callback) {
  64964. if (this._onBeforeRenderObserver) {
  64965. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  64966. }
  64967. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  64968. },
  64969. enumerable: true,
  64970. configurable: true
  64971. });
  64972. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  64973. /**
  64974. * A function that is added to the onAfterRenderObservable
  64975. */
  64976. set: function (callback) {
  64977. if (this._onAfterRenderObserver) {
  64978. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  64979. }
  64980. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  64981. },
  64982. enumerable: true,
  64983. configurable: true
  64984. });
  64985. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  64986. /**
  64987. * 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
  64988. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  64989. */
  64990. get: function () {
  64991. return this._textures.data[this._currentRenderTextureInd];
  64992. },
  64993. set: function (value) {
  64994. this._forcedOutputTexture = value;
  64995. },
  64996. enumerable: true,
  64997. configurable: true
  64998. });
  64999. /**
  65000. * Gets the camera which post process is applied to.
  65001. * @returns The camera the post process is applied to.
  65002. */
  65003. PostProcess.prototype.getCamera = function () {
  65004. return this._camera;
  65005. };
  65006. Object.defineProperty(PostProcess.prototype, "texelSize", {
  65007. /**
  65008. * Gets the texel size of the postprocess.
  65009. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  65010. */
  65011. get: function () {
  65012. if (this._shareOutputWithPostProcess) {
  65013. return this._shareOutputWithPostProcess.texelSize;
  65014. }
  65015. if (this._forcedOutputTexture) {
  65016. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  65017. }
  65018. return this._texelSize;
  65019. },
  65020. enumerable: true,
  65021. configurable: true
  65022. });
  65023. /**
  65024. * Gets the engine which this post process belongs to.
  65025. * @returns The engine the post process was enabled with.
  65026. */
  65027. PostProcess.prototype.getEngine = function () {
  65028. return this._engine;
  65029. };
  65030. /**
  65031. * The effect that is created when initializing the post process.
  65032. * @returns The created effect corrisponding the the postprocess.
  65033. */
  65034. PostProcess.prototype.getEffect = function () {
  65035. return this._effect;
  65036. };
  65037. /**
  65038. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  65039. * @param postProcess The post process to share the output with.
  65040. * @returns This post process.
  65041. */
  65042. PostProcess.prototype.shareOutputWith = function (postProcess) {
  65043. this._disposeTextures();
  65044. this._shareOutputWithPostProcess = postProcess;
  65045. return this;
  65046. };
  65047. /**
  65048. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  65049. * This should be called if the post process that shares output with this post process is disabled/disposed.
  65050. */
  65051. PostProcess.prototype.useOwnOutput = function () {
  65052. if (this._textures.length == 0) {
  65053. this._textures = new BABYLON.SmartArray(2);
  65054. }
  65055. this._shareOutputWithPostProcess = null;
  65056. };
  65057. /**
  65058. * Updates the effect with the current post process compile time values and recompiles the shader.
  65059. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  65060. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  65061. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  65062. * @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
  65063. * @param onCompiled Called when the shader has been compiled.
  65064. * @param onError Called if there is an error when compiling a shader.
  65065. */
  65066. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  65067. if (defines === void 0) { defines = null; }
  65068. if (uniforms === void 0) { uniforms = null; }
  65069. if (samplers === void 0) { samplers = null; }
  65070. 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);
  65071. };
  65072. /**
  65073. * The post process is reusable if it can be used multiple times within one frame.
  65074. * @returns If the post process is reusable
  65075. */
  65076. PostProcess.prototype.isReusable = function () {
  65077. return this._reusable;
  65078. };
  65079. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  65080. PostProcess.prototype.markTextureDirty = function () {
  65081. this.width = -1;
  65082. };
  65083. /**
  65084. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  65085. * 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.
  65086. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  65087. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  65088. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  65089. * @returns The target texture that was bound to be written to.
  65090. */
  65091. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  65092. var _this = this;
  65093. if (sourceTexture === void 0) { sourceTexture = null; }
  65094. camera = camera || this._camera;
  65095. var scene = camera.getScene();
  65096. var engine = scene.getEngine();
  65097. var maxSize = engine.getCaps().maxTextureSize;
  65098. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  65099. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  65100. // 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
  65101. var webVRCamera = camera.parent;
  65102. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  65103. requiredWidth /= 2;
  65104. }
  65105. var desiredWidth = (this._options.width || requiredWidth);
  65106. var desiredHeight = this._options.height || requiredHeight;
  65107. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  65108. if (this.adaptScaleToCurrentViewport) {
  65109. var currentViewport = engine.currentViewport;
  65110. if (currentViewport) {
  65111. desiredWidth *= currentViewport.width;
  65112. desiredHeight *= currentViewport.height;
  65113. }
  65114. }
  65115. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  65116. if (!this._options.width) {
  65117. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  65118. }
  65119. if (!this._options.height) {
  65120. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  65121. }
  65122. }
  65123. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  65124. if (this._textures.length > 0) {
  65125. for (var i = 0; i < this._textures.length; i++) {
  65126. this._engine._releaseTexture(this._textures.data[i]);
  65127. }
  65128. this._textures.reset();
  65129. }
  65130. this.width = desiredWidth;
  65131. this.height = desiredHeight;
  65132. var textureSize = { width: this.width, height: this.height };
  65133. var textureOptions = {
  65134. generateMipMaps: false,
  65135. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  65136. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  65137. samplingMode: this.renderTargetSamplingMode,
  65138. type: this._textureType
  65139. };
  65140. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65141. if (this._reusable) {
  65142. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65143. }
  65144. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  65145. this.onSizeChangedObservable.notifyObservers(this);
  65146. }
  65147. this._textures.forEach(function (texture) {
  65148. if (texture.samples !== _this.samples) {
  65149. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  65150. }
  65151. });
  65152. }
  65153. var target;
  65154. if (this._shareOutputWithPostProcess) {
  65155. target = this._shareOutputWithPostProcess.inputTexture;
  65156. }
  65157. else if (this._forcedOutputTexture) {
  65158. target = this._forcedOutputTexture;
  65159. this.width = this._forcedOutputTexture.width;
  65160. this.height = this._forcedOutputTexture.height;
  65161. }
  65162. else {
  65163. target = this.inputTexture;
  65164. }
  65165. // Bind the input of this post process to be used as the output of the previous post process.
  65166. if (this.enablePixelPerfectMode) {
  65167. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  65168. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  65169. }
  65170. else {
  65171. this._scaleRatio.copyFromFloats(1, 1);
  65172. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  65173. }
  65174. this.onActivateObservable.notifyObservers(camera);
  65175. // Clear
  65176. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  65177. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  65178. }
  65179. if (this._reusable) {
  65180. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  65181. }
  65182. return target;
  65183. };
  65184. Object.defineProperty(PostProcess.prototype, "isSupported", {
  65185. /**
  65186. * If the post process is supported.
  65187. */
  65188. get: function () {
  65189. return this._effect.isSupported;
  65190. },
  65191. enumerable: true,
  65192. configurable: true
  65193. });
  65194. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  65195. /**
  65196. * The aspect ratio of the output texture.
  65197. */
  65198. get: function () {
  65199. if (this._shareOutputWithPostProcess) {
  65200. return this._shareOutputWithPostProcess.aspectRatio;
  65201. }
  65202. if (this._forcedOutputTexture) {
  65203. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  65204. }
  65205. return this.width / this.height;
  65206. },
  65207. enumerable: true,
  65208. configurable: true
  65209. });
  65210. /**
  65211. * Get a value indicating if the post-process is ready to be used
  65212. * @returns true if the post-process is ready (shader is compiled)
  65213. */
  65214. PostProcess.prototype.isReady = function () {
  65215. return this._effect && this._effect.isReady();
  65216. };
  65217. /**
  65218. * Binds all textures and uniforms to the shader, this will be run on every pass.
  65219. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  65220. */
  65221. PostProcess.prototype.apply = function () {
  65222. // Check
  65223. if (!this._effect || !this._effect.isReady())
  65224. return null;
  65225. // States
  65226. this._engine.enableEffect(this._effect);
  65227. this._engine.setState(false);
  65228. this._engine.setDepthBuffer(false);
  65229. this._engine.setDepthWrite(false);
  65230. // Alpha
  65231. this._engine.setAlphaMode(this.alphaMode);
  65232. if (this.alphaConstants) {
  65233. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  65234. }
  65235. // Bind the output texture of the preivous post process as the input to this post process.
  65236. var source;
  65237. if (this._shareOutputWithPostProcess) {
  65238. source = this._shareOutputWithPostProcess.inputTexture;
  65239. }
  65240. else if (this._forcedOutputTexture) {
  65241. source = this._forcedOutputTexture;
  65242. }
  65243. else {
  65244. source = this.inputTexture;
  65245. }
  65246. this._effect._bindTexture("textureSampler", source);
  65247. // Parameters
  65248. this._effect.setVector2("scale", this._scaleRatio);
  65249. this.onApplyObservable.notifyObservers(this._effect);
  65250. return this._effect;
  65251. };
  65252. PostProcess.prototype._disposeTextures = function () {
  65253. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  65254. return;
  65255. }
  65256. if (this._textures.length > 0) {
  65257. for (var i = 0; i < this._textures.length; i++) {
  65258. this._engine._releaseTexture(this._textures.data[i]);
  65259. }
  65260. }
  65261. this._textures.dispose();
  65262. };
  65263. /**
  65264. * Disposes the post process.
  65265. * @param camera The camera to dispose the post process on.
  65266. */
  65267. PostProcess.prototype.dispose = function (camera) {
  65268. camera = camera || this._camera;
  65269. this._disposeTextures();
  65270. if (this._scene) {
  65271. var index_1 = this._scene.postProcesses.indexOf(this);
  65272. if (index_1 !== -1) {
  65273. this._scene.postProcesses.splice(index_1, 1);
  65274. }
  65275. }
  65276. else {
  65277. var index_2 = this._engine.postProcesses.indexOf(this);
  65278. if (index_2 !== -1) {
  65279. this._engine.postProcesses.splice(index_2, 1);
  65280. }
  65281. }
  65282. if (!camera) {
  65283. return;
  65284. }
  65285. camera.detachPostProcess(this);
  65286. var index = camera._postProcesses.indexOf(this);
  65287. if (index === 0 && camera._postProcesses.length > 0) {
  65288. var firstPostProcess = this._camera._getFirstPostProcess();
  65289. if (firstPostProcess) {
  65290. firstPostProcess.markTextureDirty();
  65291. }
  65292. }
  65293. this.onActivateObservable.clear();
  65294. this.onAfterRenderObservable.clear();
  65295. this.onApplyObservable.clear();
  65296. this.onBeforeRenderObservable.clear();
  65297. this.onSizeChangedObservable.clear();
  65298. };
  65299. return PostProcess;
  65300. }());
  65301. BABYLON.PostProcess = PostProcess;
  65302. })(BABYLON || (BABYLON = {}));
  65303. //# sourceMappingURL=babylon.postProcess.js.map
  65304. var BABYLON;
  65305. (function (BABYLON) {
  65306. var PassPostProcess = /** @class */ (function (_super) {
  65307. __extends(PassPostProcess, _super);
  65308. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  65309. if (camera === void 0) { camera = null; }
  65310. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65311. if (blockCompilation === void 0) { blockCompilation = false; }
  65312. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  65313. }
  65314. return PassPostProcess;
  65315. }(BABYLON.PostProcess));
  65316. BABYLON.PassPostProcess = PassPostProcess;
  65317. })(BABYLON || (BABYLON = {}));
  65318. //# sourceMappingURL=babylon.passPostProcess.js.map
  65319. var __assign = (this && this.__assign) || Object.assign || function(t) {
  65320. for (var s, i = 1, n = arguments.length; i < n; i++) {
  65321. s = arguments[i];
  65322. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  65323. t[p] = s[p];
  65324. }
  65325. return t;
  65326. };
  65327. var BABYLON;
  65328. (function (BABYLON) {
  65329. /**
  65330. * Default implementation IShadowGenerator.
  65331. * This is the main object responsible of generating shadows in the framework.
  65332. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  65333. */
  65334. var ShadowGenerator = /** @class */ (function () {
  65335. /**
  65336. * Creates a ShadowGenerator object.
  65337. * A ShadowGenerator is the required tool to use the shadows.
  65338. * Each light casting shadows needs to use its own ShadowGenerator.
  65339. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  65340. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  65341. * @param light The light object generating the shadows.
  65342. * @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.
  65343. */
  65344. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  65345. this._bias = 0.00005;
  65346. this._normalBias = 0;
  65347. this._blurBoxOffset = 1;
  65348. this._blurScale = 2;
  65349. this._blurKernel = 1;
  65350. this._useKernelBlur = false;
  65351. this._filter = ShadowGenerator.FILTER_NONE;
  65352. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  65353. this._contactHardeningLightSizeUVRatio = 0.1;
  65354. this._darkness = 0;
  65355. this._transparencyShadow = false;
  65356. /**
  65357. * Controls the extent to which the shadows fade out at the edge of the frustum
  65358. * Used only by directionals and spots
  65359. */
  65360. this.frustumEdgeFalloff = 0;
  65361. /**
  65362. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  65363. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  65364. * It might on the other hand introduce peter panning.
  65365. */
  65366. this.forceBackFacesOnly = false;
  65367. this._lightDirection = BABYLON.Vector3.Zero();
  65368. this._viewMatrix = BABYLON.Matrix.Zero();
  65369. this._projectionMatrix = BABYLON.Matrix.Zero();
  65370. this._transformMatrix = BABYLON.Matrix.Zero();
  65371. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  65372. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  65373. this._currentFaceIndex = 0;
  65374. this._currentFaceIndexCache = 0;
  65375. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  65376. this._mapSize = mapSize;
  65377. this._light = light;
  65378. this._scene = light.getScene();
  65379. light._shadowGenerator = this;
  65380. // Texture type fallback from float to int if not supported.
  65381. var caps = this._scene.getEngine().getCaps();
  65382. if (!useFullFloatFirst) {
  65383. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  65384. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65385. }
  65386. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  65387. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65388. }
  65389. else {
  65390. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65391. }
  65392. }
  65393. else {
  65394. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  65395. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65396. }
  65397. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  65398. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65399. }
  65400. else {
  65401. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65402. }
  65403. }
  65404. this._initializeGenerator();
  65405. this._applyFilterValues();
  65406. }
  65407. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  65408. /**
  65409. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  65410. */
  65411. get: function () {
  65412. return this._bias;
  65413. },
  65414. /**
  65415. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  65416. */
  65417. set: function (bias) {
  65418. this._bias = bias;
  65419. },
  65420. enumerable: true,
  65421. configurable: true
  65422. });
  65423. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  65424. /**
  65425. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  65426. */
  65427. get: function () {
  65428. return this._normalBias;
  65429. },
  65430. /**
  65431. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  65432. */
  65433. set: function (normalBias) {
  65434. this._normalBias = normalBias;
  65435. },
  65436. enumerable: true,
  65437. configurable: true
  65438. });
  65439. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  65440. /**
  65441. * Gets the blur box offset: offset applied during the blur pass.
  65442. * Only usefull if useKernelBlur = false
  65443. */
  65444. get: function () {
  65445. return this._blurBoxOffset;
  65446. },
  65447. /**
  65448. * Sets the blur box offset: offset applied during the blur pass.
  65449. * Only usefull if useKernelBlur = false
  65450. */
  65451. set: function (value) {
  65452. if (this._blurBoxOffset === value) {
  65453. return;
  65454. }
  65455. this._blurBoxOffset = value;
  65456. this._disposeBlurPostProcesses();
  65457. },
  65458. enumerable: true,
  65459. configurable: true
  65460. });
  65461. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  65462. /**
  65463. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  65464. * 2 means half of the size.
  65465. */
  65466. get: function () {
  65467. return this._blurScale;
  65468. },
  65469. /**
  65470. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  65471. * 2 means half of the size.
  65472. */
  65473. set: function (value) {
  65474. if (this._blurScale === value) {
  65475. return;
  65476. }
  65477. this._blurScale = value;
  65478. this._disposeBlurPostProcesses();
  65479. },
  65480. enumerable: true,
  65481. configurable: true
  65482. });
  65483. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  65484. /**
  65485. * Gets the blur kernel: kernel size of the blur pass.
  65486. * Only usefull if useKernelBlur = true
  65487. */
  65488. get: function () {
  65489. return this._blurKernel;
  65490. },
  65491. /**
  65492. * Sets the blur kernel: kernel size of the blur pass.
  65493. * Only usefull if useKernelBlur = true
  65494. */
  65495. set: function (value) {
  65496. if (this._blurKernel === value) {
  65497. return;
  65498. }
  65499. this._blurKernel = value;
  65500. this._disposeBlurPostProcesses();
  65501. },
  65502. enumerable: true,
  65503. configurable: true
  65504. });
  65505. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  65506. /**
  65507. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  65508. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  65509. */
  65510. get: function () {
  65511. return this._useKernelBlur;
  65512. },
  65513. /**
  65514. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  65515. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  65516. */
  65517. set: function (value) {
  65518. if (this._useKernelBlur === value) {
  65519. return;
  65520. }
  65521. this._useKernelBlur = value;
  65522. this._disposeBlurPostProcesses();
  65523. },
  65524. enumerable: true,
  65525. configurable: true
  65526. });
  65527. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  65528. /**
  65529. * Gets the depth scale used in ESM mode.
  65530. */
  65531. get: function () {
  65532. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  65533. },
  65534. /**
  65535. * Sets the depth scale used in ESM mode.
  65536. * This can override the scale stored on the light.
  65537. */
  65538. set: function (value) {
  65539. this._depthScale = value;
  65540. },
  65541. enumerable: true,
  65542. configurable: true
  65543. });
  65544. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  65545. /**
  65546. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  65547. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  65548. */
  65549. get: function () {
  65550. return this._filter;
  65551. },
  65552. /**
  65553. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  65554. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  65555. */
  65556. set: function (value) {
  65557. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  65558. if (this._light.needCube()) {
  65559. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  65560. this.useExponentialShadowMap = true;
  65561. return;
  65562. }
  65563. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  65564. this.useCloseExponentialShadowMap = true;
  65565. return;
  65566. }
  65567. // PCF on cubemap would also be expensive
  65568. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  65569. this.usePoissonSampling = true;
  65570. return;
  65571. }
  65572. }
  65573. // Weblg1 fallback for PCF.
  65574. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  65575. if (this._scene.getEngine().webGLVersion === 1) {
  65576. this.usePoissonSampling = true;
  65577. return;
  65578. }
  65579. }
  65580. if (this._filter === value) {
  65581. return;
  65582. }
  65583. this._filter = value;
  65584. this._disposeBlurPostProcesses();
  65585. this._applyFilterValues();
  65586. this._light._markMeshesAsLightDirty();
  65587. },
  65588. enumerable: true,
  65589. configurable: true
  65590. });
  65591. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  65592. /**
  65593. * Gets if the current filter is set to Poisson Sampling.
  65594. */
  65595. get: function () {
  65596. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  65597. },
  65598. /**
  65599. * Sets the current filter to Poisson Sampling.
  65600. */
  65601. set: function (value) {
  65602. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  65603. return;
  65604. }
  65605. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  65606. },
  65607. enumerable: true,
  65608. configurable: true
  65609. });
  65610. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  65611. /**
  65612. * Gets if the current filter is set to VSM.
  65613. * DEPRECATED. Should use useExponentialShadowMap instead.
  65614. */
  65615. get: function () {
  65616. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  65617. return this.useExponentialShadowMap;
  65618. },
  65619. /**
  65620. * Sets the current filter is to VSM.
  65621. * DEPRECATED. Should use useExponentialShadowMap instead.
  65622. */
  65623. set: function (value) {
  65624. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  65625. this.useExponentialShadowMap = value;
  65626. },
  65627. enumerable: true,
  65628. configurable: true
  65629. });
  65630. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  65631. /**
  65632. * Gets if the current filter is set to blurred VSM.
  65633. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  65634. */
  65635. get: function () {
  65636. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  65637. return this.useBlurExponentialShadowMap;
  65638. },
  65639. /**
  65640. * Sets the current filter is to blurred VSM.
  65641. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  65642. */
  65643. set: function (value) {
  65644. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  65645. this.useBlurExponentialShadowMap = value;
  65646. },
  65647. enumerable: true,
  65648. configurable: true
  65649. });
  65650. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  65651. /**
  65652. * Gets if the current filter is set to ESM.
  65653. */
  65654. get: function () {
  65655. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  65656. },
  65657. /**
  65658. * Sets the current filter is to ESM.
  65659. */
  65660. set: function (value) {
  65661. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  65662. return;
  65663. }
  65664. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65665. },
  65666. enumerable: true,
  65667. configurable: true
  65668. });
  65669. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  65670. /**
  65671. * Gets if the current filter is set to filtered ESM.
  65672. */
  65673. get: function () {
  65674. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  65675. },
  65676. /**
  65677. * Gets if the current filter is set to filtered ESM.
  65678. */
  65679. set: function (value) {
  65680. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  65681. return;
  65682. }
  65683. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65684. },
  65685. enumerable: true,
  65686. configurable: true
  65687. });
  65688. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  65689. /**
  65690. * Gets if the current filter is set to "close ESM" (using the inverse of the
  65691. * exponential to prevent steep falloff artifacts).
  65692. */
  65693. get: function () {
  65694. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  65695. },
  65696. /**
  65697. * Sets the current filter to "close ESM" (using the inverse of the
  65698. * exponential to prevent steep falloff artifacts).
  65699. */
  65700. set: function (value) {
  65701. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  65702. return;
  65703. }
  65704. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65705. },
  65706. enumerable: true,
  65707. configurable: true
  65708. });
  65709. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  65710. /**
  65711. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  65712. * exponential to prevent steep falloff artifacts).
  65713. */
  65714. get: function () {
  65715. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  65716. },
  65717. /**
  65718. * Sets the current filter to filtered "close ESM" (using the inverse of the
  65719. * exponential to prevent steep falloff artifacts).
  65720. */
  65721. set: function (value) {
  65722. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  65723. return;
  65724. }
  65725. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65726. },
  65727. enumerable: true,
  65728. configurable: true
  65729. });
  65730. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  65731. /**
  65732. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  65733. */
  65734. get: function () {
  65735. return this.filter === ShadowGenerator.FILTER_PCF;
  65736. },
  65737. /**
  65738. * Sets the current filter to "PCF" (percentage closer filtering).
  65739. */
  65740. set: function (value) {
  65741. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  65742. return;
  65743. }
  65744. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  65745. },
  65746. enumerable: true,
  65747. configurable: true
  65748. });
  65749. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  65750. /**
  65751. * Gets the PCF or PCSS Quality.
  65752. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  65753. */
  65754. get: function () {
  65755. return this._filteringQuality;
  65756. },
  65757. /**
  65758. * Sets the PCF or PCSS Quality.
  65759. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  65760. */
  65761. set: function (filteringQuality) {
  65762. this._filteringQuality = filteringQuality;
  65763. },
  65764. enumerable: true,
  65765. configurable: true
  65766. });
  65767. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  65768. /**
  65769. * Gets if the current filter is set to "PCSS" (contact hardening).
  65770. */
  65771. get: function () {
  65772. return this.filter === ShadowGenerator.FILTER_PCSS;
  65773. },
  65774. /**
  65775. * Sets the current filter to "PCSS" (contact hardening).
  65776. */
  65777. set: function (value) {
  65778. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  65779. return;
  65780. }
  65781. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  65782. },
  65783. enumerable: true,
  65784. configurable: true
  65785. });
  65786. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  65787. /**
  65788. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  65789. * Using a ratio helps keeping shape stability independently of the map size.
  65790. *
  65791. * It does not account for the light projection as it was having too much
  65792. * instability during the light setup or during light position changes.
  65793. *
  65794. * Only valid if useContactHardeningShadow is true.
  65795. */
  65796. get: function () {
  65797. return this._contactHardeningLightSizeUVRatio;
  65798. },
  65799. /**
  65800. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  65801. * Using a ratio helps keeping shape stability independently of the map size.
  65802. *
  65803. * It does not account for the light projection as it was having too much
  65804. * instability during the light setup or during light position changes.
  65805. *
  65806. * Only valid if useContactHardeningShadow is true.
  65807. */
  65808. set: function (contactHardeningLightSizeUVRatio) {
  65809. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  65810. },
  65811. enumerable: true,
  65812. configurable: true
  65813. });
  65814. /**
  65815. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  65816. * 0 means strongest and 1 would means no shadow.
  65817. * @returns the darkness.
  65818. */
  65819. ShadowGenerator.prototype.getDarkness = function () {
  65820. return this._darkness;
  65821. };
  65822. /**
  65823. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  65824. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  65825. * @returns the shadow generator allowing fluent coding.
  65826. */
  65827. ShadowGenerator.prototype.setDarkness = function (darkness) {
  65828. if (darkness >= 1.0)
  65829. this._darkness = 1.0;
  65830. else if (darkness <= 0.0)
  65831. this._darkness = 0.0;
  65832. else
  65833. this._darkness = darkness;
  65834. return this;
  65835. };
  65836. /**
  65837. * Sets the ability to have transparent shadow (boolean).
  65838. * @param transparent True if transparent else False
  65839. * @returns the shadow generator allowing fluent coding
  65840. */
  65841. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  65842. this._transparencyShadow = transparent;
  65843. return this;
  65844. };
  65845. /**
  65846. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  65847. * @returns The render target texture if present otherwise, null
  65848. */
  65849. ShadowGenerator.prototype.getShadowMap = function () {
  65850. return this._shadowMap;
  65851. };
  65852. /**
  65853. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  65854. * @returns The render target texture if the shadow map is present otherwise, null
  65855. */
  65856. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  65857. if (this._shadowMap2) {
  65858. return this._shadowMap2;
  65859. }
  65860. return this._shadowMap;
  65861. };
  65862. /**
  65863. * Helper function to add a mesh and its descendants to the list of shadow casters.
  65864. * @param mesh Mesh to add
  65865. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  65866. * @returns the Shadow Generator itself
  65867. */
  65868. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  65869. if (includeDescendants === void 0) { includeDescendants = true; }
  65870. if (!this._shadowMap) {
  65871. return this;
  65872. }
  65873. if (!this._shadowMap.renderList) {
  65874. this._shadowMap.renderList = [];
  65875. }
  65876. this._shadowMap.renderList.push(mesh);
  65877. if (includeDescendants) {
  65878. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  65879. }
  65880. return this;
  65881. var _a;
  65882. };
  65883. /**
  65884. * Helper function to remove a mesh and its descendants from the list of shadow casters
  65885. * @param mesh Mesh to remove
  65886. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  65887. * @returns the Shadow Generator itself
  65888. */
  65889. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  65890. if (includeDescendants === void 0) { includeDescendants = true; }
  65891. if (!this._shadowMap || !this._shadowMap.renderList) {
  65892. return this;
  65893. }
  65894. var index = this._shadowMap.renderList.indexOf(mesh);
  65895. if (index !== -1) {
  65896. this._shadowMap.renderList.splice(index, 1);
  65897. }
  65898. if (includeDescendants) {
  65899. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  65900. var child = _a[_i];
  65901. this.removeShadowCaster(child);
  65902. }
  65903. }
  65904. return this;
  65905. };
  65906. /**
  65907. * Returns the associated light object.
  65908. * @returns the light generating the shadow
  65909. */
  65910. ShadowGenerator.prototype.getLight = function () {
  65911. return this._light;
  65912. };
  65913. ShadowGenerator.prototype._initializeGenerator = function () {
  65914. this._light._markMeshesAsLightDirty();
  65915. this._initializeShadowMap();
  65916. };
  65917. ShadowGenerator.prototype._initializeShadowMap = function () {
  65918. var _this = this;
  65919. // Render target
  65920. var engine = this._scene.getEngine();
  65921. if (engine.webGLVersion > 1) {
  65922. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  65923. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  65924. }
  65925. else {
  65926. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  65927. }
  65928. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65929. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65930. this._shadowMap.anisotropicFilteringLevel = 1;
  65931. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65932. this._shadowMap.renderParticles = false;
  65933. this._shadowMap.ignoreCameraViewport = true;
  65934. // Record Face Index before render.
  65935. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  65936. _this._currentFaceIndex = faceIndex;
  65937. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  65938. engine.setColorWrite(false);
  65939. }
  65940. });
  65941. // Custom render function.
  65942. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  65943. // Blur if required afer render.
  65944. this._shadowMap.onAfterUnbindObservable.add(function () {
  65945. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  65946. engine.setColorWrite(true);
  65947. }
  65948. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  65949. return;
  65950. }
  65951. var shadowMap = _this.getShadowMapForRendering();
  65952. if (shadowMap) {
  65953. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  65954. }
  65955. });
  65956. // Clear according to the chosen filter.
  65957. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  65958. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  65959. this._shadowMap.onClearObservable.add(function (engine) {
  65960. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  65961. engine.clear(clearOne, false, true, false);
  65962. }
  65963. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  65964. engine.clear(clearZero, true, true, false);
  65965. }
  65966. else {
  65967. engine.clear(clearOne, true, true, false);
  65968. }
  65969. });
  65970. };
  65971. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  65972. var _this = this;
  65973. var engine = this._scene.getEngine();
  65974. var targetSize = this._mapSize / this.blurScale;
  65975. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  65976. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  65977. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65978. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65979. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  65980. }
  65981. if (this.useKernelBlur) {
  65982. 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);
  65983. this._kernelBlurXPostprocess.width = targetSize;
  65984. this._kernelBlurXPostprocess.height = targetSize;
  65985. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  65986. effect.setTexture("textureSampler", _this._shadowMap);
  65987. });
  65988. 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);
  65989. this._kernelBlurXPostprocess.autoClear = false;
  65990. this._kernelBlurYPostprocess.autoClear = false;
  65991. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  65992. this._kernelBlurXPostprocess.packedFloat = true;
  65993. this._kernelBlurYPostprocess.packedFloat = true;
  65994. }
  65995. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  65996. }
  65997. else {
  65998. 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);
  65999. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  66000. effect.setFloat2("screenSize", targetSize, targetSize);
  66001. effect.setTexture("textureSampler", _this._shadowMap);
  66002. });
  66003. this._boxBlurPostprocess.autoClear = false;
  66004. this._blurPostProcesses = [this._boxBlurPostprocess];
  66005. }
  66006. };
  66007. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  66008. var index;
  66009. var engine = this._scene.getEngine();
  66010. if (depthOnlySubMeshes.length) {
  66011. engine.setColorWrite(false);
  66012. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  66013. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  66014. }
  66015. engine.setColorWrite(true);
  66016. }
  66017. for (index = 0; index < opaqueSubMeshes.length; index++) {
  66018. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  66019. }
  66020. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  66021. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  66022. }
  66023. if (this._transparencyShadow) {
  66024. for (index = 0; index < transparentSubMeshes.length; index++) {
  66025. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  66026. }
  66027. }
  66028. };
  66029. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  66030. var _this = this;
  66031. var mesh = subMesh.getRenderingMesh();
  66032. var scene = this._scene;
  66033. var engine = scene.getEngine();
  66034. var material = subMesh.getMaterial();
  66035. if (!material) {
  66036. return;
  66037. }
  66038. // Culling
  66039. engine.setState(material.backFaceCulling);
  66040. // Managing instances
  66041. var batch = mesh._getInstancesRenderList(subMesh._id);
  66042. if (batch.mustReturn) {
  66043. return;
  66044. }
  66045. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  66046. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  66047. engine.enableEffect(this._effect);
  66048. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  66049. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  66050. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  66051. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66052. this._effect.setVector3("lightData", this._cachedDirection);
  66053. }
  66054. else {
  66055. this._effect.setVector3("lightData", this._cachedPosition);
  66056. }
  66057. if (scene.activeCamera) {
  66058. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  66059. }
  66060. // Alpha test
  66061. if (material && material.needAlphaTesting()) {
  66062. var alphaTexture = material.getAlphaTestTexture();
  66063. if (alphaTexture) {
  66064. this._effect.setTexture("diffuseSampler", alphaTexture);
  66065. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  66066. }
  66067. }
  66068. // Bones
  66069. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66070. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  66071. }
  66072. // Morph targets
  66073. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  66074. if (this.forceBackFacesOnly) {
  66075. engine.setState(true, 0, false, true);
  66076. }
  66077. // Draw
  66078. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  66079. if (this.forceBackFacesOnly) {
  66080. engine.setState(true, 0, false, false);
  66081. }
  66082. }
  66083. else {
  66084. // Need to reset refresh rate of the shadowMap
  66085. if (this._shadowMap) {
  66086. this._shadowMap.resetRefreshCounter();
  66087. }
  66088. }
  66089. };
  66090. ShadowGenerator.prototype._applyFilterValues = function () {
  66091. if (!this._shadowMap) {
  66092. return;
  66093. }
  66094. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  66095. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  66096. }
  66097. else {
  66098. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66099. }
  66100. };
  66101. /**
  66102. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66103. * @param onCompiled Callback triggered at the and of the effects compilation
  66104. * @param options Sets of optional options forcing the compilation with different modes
  66105. */
  66106. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  66107. var _this = this;
  66108. var localOptions = __assign({ useInstances: false }, options);
  66109. var shadowMap = this.getShadowMap();
  66110. if (!shadowMap) {
  66111. if (onCompiled) {
  66112. onCompiled(this);
  66113. }
  66114. return;
  66115. }
  66116. var renderList = shadowMap.renderList;
  66117. if (!renderList) {
  66118. if (onCompiled) {
  66119. onCompiled(this);
  66120. }
  66121. return;
  66122. }
  66123. var subMeshes = new Array();
  66124. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  66125. var mesh = renderList_1[_i];
  66126. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  66127. }
  66128. if (subMeshes.length === 0) {
  66129. if (onCompiled) {
  66130. onCompiled(this);
  66131. }
  66132. return;
  66133. }
  66134. var currentIndex = 0;
  66135. var checkReady = function () {
  66136. if (!_this._scene || !_this._scene.getEngine()) {
  66137. return;
  66138. }
  66139. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  66140. currentIndex++;
  66141. if (currentIndex >= subMeshes.length) {
  66142. if (onCompiled) {
  66143. onCompiled(_this);
  66144. }
  66145. return;
  66146. }
  66147. }
  66148. setTimeout(checkReady, 16);
  66149. };
  66150. checkReady();
  66151. };
  66152. /**
  66153. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66154. * @param options Sets of optional options forcing the compilation with different modes
  66155. * @returns A promise that resolves when the compilation completes
  66156. */
  66157. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  66158. var _this = this;
  66159. return new Promise(function (resolve) {
  66160. _this.forceCompilation(function () {
  66161. resolve();
  66162. }, options);
  66163. });
  66164. };
  66165. /**
  66166. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  66167. * @param subMesh The submesh we want to render in the shadow map
  66168. * @param useInstances Defines wether will draw in the map using instances
  66169. * @returns true if ready otherwise, false
  66170. */
  66171. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  66172. var defines = [];
  66173. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66174. defines.push("#define FLOAT");
  66175. }
  66176. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66177. defines.push("#define ESM");
  66178. }
  66179. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  66180. defines.push("#define DEPTHTEXTURE");
  66181. }
  66182. var attribs = [BABYLON.VertexBuffer.PositionKind];
  66183. var mesh = subMesh.getMesh();
  66184. var material = subMesh.getMaterial();
  66185. // Normal bias.
  66186. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  66187. attribs.push(BABYLON.VertexBuffer.NormalKind);
  66188. defines.push("#define NORMAL");
  66189. if (mesh.nonUniformScaling) {
  66190. defines.push("#define NONUNIFORMSCALING");
  66191. }
  66192. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66193. defines.push("#define DIRECTIONINLIGHTDATA");
  66194. }
  66195. }
  66196. // Alpha test
  66197. if (material && material.needAlphaTesting()) {
  66198. var alphaTexture = material.getAlphaTestTexture();
  66199. if (alphaTexture) {
  66200. defines.push("#define ALPHATEST");
  66201. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  66202. attribs.push(BABYLON.VertexBuffer.UVKind);
  66203. defines.push("#define UV1");
  66204. }
  66205. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  66206. if (alphaTexture.coordinatesIndex === 1) {
  66207. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  66208. defines.push("#define UV2");
  66209. }
  66210. }
  66211. }
  66212. }
  66213. // Bones
  66214. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66215. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  66216. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  66217. if (mesh.numBoneInfluencers > 4) {
  66218. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  66219. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  66220. }
  66221. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  66222. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  66223. }
  66224. else {
  66225. defines.push("#define NUM_BONE_INFLUENCERS 0");
  66226. }
  66227. // Morph targets
  66228. var manager = mesh.morphTargetManager;
  66229. var morphInfluencers = 0;
  66230. if (manager) {
  66231. if (manager.numInfluencers > 0) {
  66232. defines.push("#define MORPHTARGETS");
  66233. morphInfluencers = manager.numInfluencers;
  66234. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  66235. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  66236. }
  66237. }
  66238. // Instances
  66239. if (useInstances) {
  66240. defines.push("#define INSTANCES");
  66241. attribs.push("world0");
  66242. attribs.push("world1");
  66243. attribs.push("world2");
  66244. attribs.push("world3");
  66245. }
  66246. // Get correct effect
  66247. var join = defines.join("\n");
  66248. if (this._cachedDefines !== join) {
  66249. this._cachedDefines = join;
  66250. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  66251. }
  66252. if (!this._effect.isReady()) {
  66253. return false;
  66254. }
  66255. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66256. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  66257. this._initializeBlurRTTAndPostProcesses();
  66258. }
  66259. }
  66260. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  66261. return false;
  66262. }
  66263. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  66264. return false;
  66265. }
  66266. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  66267. return false;
  66268. }
  66269. return true;
  66270. };
  66271. /**
  66272. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  66273. * @param defines Defines of the material we want to update
  66274. * @param lightIndex Index of the light in the enabled light list of the material
  66275. */
  66276. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  66277. var scene = this._scene;
  66278. var light = this._light;
  66279. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  66280. return;
  66281. }
  66282. defines["SHADOW" + lightIndex] = true;
  66283. if (this.useContactHardeningShadow) {
  66284. defines["SHADOWPCSS" + lightIndex] = true;
  66285. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66286. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66287. }
  66288. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66289. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66290. }
  66291. // else default to high.
  66292. }
  66293. if (this.usePercentageCloserFiltering) {
  66294. defines["SHADOWPCF" + lightIndex] = true;
  66295. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66296. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66297. }
  66298. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66299. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66300. }
  66301. // else default to high.
  66302. }
  66303. else if (this.usePoissonSampling) {
  66304. defines["SHADOWPOISSON" + lightIndex] = true;
  66305. }
  66306. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66307. defines["SHADOWESM" + lightIndex] = true;
  66308. }
  66309. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66310. defines["SHADOWCLOSEESM" + lightIndex] = true;
  66311. }
  66312. if (light.needCube()) {
  66313. defines["SHADOWCUBE" + lightIndex] = true;
  66314. }
  66315. };
  66316. /**
  66317. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  66318. * defined in the generator but impacting the effect).
  66319. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  66320. * @param effect The effect we are binfing the information for
  66321. */
  66322. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  66323. var light = this._light;
  66324. var scene = this._scene;
  66325. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  66326. return;
  66327. }
  66328. var camera = scene.activeCamera;
  66329. if (!camera) {
  66330. return;
  66331. }
  66332. var shadowMap = this.getShadowMap();
  66333. if (!shadowMap) {
  66334. return;
  66335. }
  66336. if (!light.needCube()) {
  66337. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  66338. }
  66339. // Only PCF uses depth stencil texture.
  66340. if (this._filter === ShadowGenerator.FILTER_PCF) {
  66341. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66342. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  66343. }
  66344. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  66345. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66346. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  66347. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  66348. }
  66349. else {
  66350. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66351. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  66352. }
  66353. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  66354. };
  66355. /**
  66356. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  66357. * (eq to shadow prjection matrix * light transform matrix)
  66358. * @returns The transform matrix used to create the shadow map
  66359. */
  66360. ShadowGenerator.prototype.getTransformMatrix = function () {
  66361. var scene = this._scene;
  66362. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  66363. return this._transformMatrix;
  66364. }
  66365. this._currentRenderID = scene.getRenderId();
  66366. this._currentFaceIndexCache = this._currentFaceIndex;
  66367. var lightPosition = this._light.position;
  66368. if (this._light.computeTransformedInformation()) {
  66369. lightPosition = this._light.transformedPosition;
  66370. }
  66371. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  66372. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  66373. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  66374. }
  66375. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  66376. this._cachedPosition.copyFrom(lightPosition);
  66377. this._cachedDirection.copyFrom(this._lightDirection);
  66378. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  66379. var shadowMap = this.getShadowMap();
  66380. if (shadowMap) {
  66381. var renderList = shadowMap.renderList;
  66382. if (renderList) {
  66383. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  66384. }
  66385. }
  66386. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  66387. }
  66388. return this._transformMatrix;
  66389. };
  66390. /**
  66391. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  66392. * Cube and 2D textures for instance.
  66393. */
  66394. ShadowGenerator.prototype.recreateShadowMap = function () {
  66395. var shadowMap = this._shadowMap;
  66396. if (!shadowMap) {
  66397. return;
  66398. }
  66399. // Track render list.
  66400. var renderList = shadowMap.renderList;
  66401. // Clean up existing data.
  66402. this._disposeRTTandPostProcesses();
  66403. // Reinitializes.
  66404. this._initializeGenerator();
  66405. // Reaffect the filter to ensure a correct fallback if necessary.
  66406. this.filter = this.filter;
  66407. // Reaffect the filter.
  66408. this._applyFilterValues();
  66409. // Reaffect Render List.
  66410. this._shadowMap.renderList = renderList;
  66411. };
  66412. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  66413. if (this._shadowMap2) {
  66414. this._shadowMap2.dispose();
  66415. this._shadowMap2 = null;
  66416. }
  66417. if (this._boxBlurPostprocess) {
  66418. this._boxBlurPostprocess.dispose();
  66419. this._boxBlurPostprocess = null;
  66420. }
  66421. if (this._kernelBlurXPostprocess) {
  66422. this._kernelBlurXPostprocess.dispose();
  66423. this._kernelBlurXPostprocess = null;
  66424. }
  66425. if (this._kernelBlurYPostprocess) {
  66426. this._kernelBlurYPostprocess.dispose();
  66427. this._kernelBlurYPostprocess = null;
  66428. }
  66429. this._blurPostProcesses = [];
  66430. };
  66431. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  66432. if (this._shadowMap) {
  66433. this._shadowMap.dispose();
  66434. this._shadowMap = null;
  66435. }
  66436. this._disposeBlurPostProcesses();
  66437. };
  66438. /**
  66439. * Disposes the ShadowGenerator.
  66440. * Returns nothing.
  66441. */
  66442. ShadowGenerator.prototype.dispose = function () {
  66443. this._disposeRTTandPostProcesses();
  66444. if (this._light) {
  66445. this._light._shadowGenerator = null;
  66446. this._light._markMeshesAsLightDirty();
  66447. }
  66448. };
  66449. /**
  66450. * Serializes the shadow generator setup to a json object.
  66451. * @returns The serialized JSON object
  66452. */
  66453. ShadowGenerator.prototype.serialize = function () {
  66454. var serializationObject = {};
  66455. var shadowMap = this.getShadowMap();
  66456. if (!shadowMap) {
  66457. return serializationObject;
  66458. }
  66459. serializationObject.lightId = this._light.id;
  66460. serializationObject.mapSize = shadowMap.getRenderSize();
  66461. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  66462. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  66463. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  66464. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  66465. serializationObject.usePoissonSampling = this.usePoissonSampling;
  66466. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  66467. serializationObject.depthScale = this.depthScale;
  66468. serializationObject.darkness = this.getDarkness();
  66469. serializationObject.blurBoxOffset = this.blurBoxOffset;
  66470. serializationObject.blurKernel = this.blurKernel;
  66471. serializationObject.blurScale = this.blurScale;
  66472. serializationObject.useKernelBlur = this.useKernelBlur;
  66473. serializationObject.transparencyShadow = this._transparencyShadow;
  66474. serializationObject.bias = this.bias;
  66475. serializationObject.normalBias = this.normalBias;
  66476. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  66477. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  66478. serializationObject.filteringQuality = this.filteringQuality;
  66479. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  66480. serializationObject.renderList = [];
  66481. if (shadowMap.renderList) {
  66482. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  66483. var mesh = shadowMap.renderList[meshIndex];
  66484. serializationObject.renderList.push(mesh.id);
  66485. }
  66486. }
  66487. return serializationObject;
  66488. };
  66489. /**
  66490. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  66491. * @param parsedShadowGenerator The JSON object to parse
  66492. * @param scene The scene to create the shadow map for
  66493. * @returns The parsed shadow generator
  66494. */
  66495. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  66496. //casting to point light, as light is missing the position attr and typescript complains.
  66497. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  66498. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  66499. var shadowMap = shadowGenerator.getShadowMap();
  66500. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  66501. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  66502. meshes.forEach(function (mesh) {
  66503. if (!shadowMap) {
  66504. return;
  66505. }
  66506. if (!shadowMap.renderList) {
  66507. shadowMap.renderList = [];
  66508. }
  66509. shadowMap.renderList.push(mesh);
  66510. });
  66511. }
  66512. if (parsedShadowGenerator.usePoissonSampling) {
  66513. shadowGenerator.usePoissonSampling = true;
  66514. }
  66515. else if (parsedShadowGenerator.useExponentialShadowMap) {
  66516. shadowGenerator.useExponentialShadowMap = true;
  66517. }
  66518. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  66519. shadowGenerator.useBlurExponentialShadowMap = true;
  66520. }
  66521. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  66522. shadowGenerator.useCloseExponentialShadowMap = true;
  66523. }
  66524. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  66525. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  66526. }
  66527. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  66528. shadowGenerator.usePercentageCloserFiltering = true;
  66529. }
  66530. else if (parsedShadowGenerator.useContactHardeningShadow) {
  66531. shadowGenerator.useContactHardeningShadow = true;
  66532. }
  66533. if (parsedShadowGenerator.filteringQuality) {
  66534. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  66535. }
  66536. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  66537. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  66538. }
  66539. // Backward compat
  66540. else if (parsedShadowGenerator.useVarianceShadowMap) {
  66541. shadowGenerator.useExponentialShadowMap = true;
  66542. }
  66543. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  66544. shadowGenerator.useBlurExponentialShadowMap = true;
  66545. }
  66546. if (parsedShadowGenerator.depthScale) {
  66547. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  66548. }
  66549. if (parsedShadowGenerator.blurScale) {
  66550. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  66551. }
  66552. if (parsedShadowGenerator.blurBoxOffset) {
  66553. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  66554. }
  66555. if (parsedShadowGenerator.useKernelBlur) {
  66556. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  66557. }
  66558. if (parsedShadowGenerator.blurKernel) {
  66559. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  66560. }
  66561. if (parsedShadowGenerator.bias !== undefined) {
  66562. shadowGenerator.bias = parsedShadowGenerator.bias;
  66563. }
  66564. if (parsedShadowGenerator.normalBias !== undefined) {
  66565. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  66566. }
  66567. if (parsedShadowGenerator.darkness) {
  66568. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  66569. }
  66570. if (parsedShadowGenerator.transparencyShadow) {
  66571. shadowGenerator.setTransparencyShadow(true);
  66572. }
  66573. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  66574. return shadowGenerator;
  66575. };
  66576. /**
  66577. * Shadow generator mode None: no filtering applied.
  66578. */
  66579. ShadowGenerator.FILTER_NONE = 0;
  66580. /**
  66581. * Shadow generator mode ESM: Exponential Shadow Mapping.
  66582. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66583. */
  66584. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  66585. /**
  66586. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  66587. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  66588. */
  66589. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  66590. /**
  66591. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  66592. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66593. */
  66594. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  66595. /**
  66596. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  66597. * edge artifacts on steep falloff.
  66598. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66599. */
  66600. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  66601. /**
  66602. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  66603. * edge artifacts on steep falloff.
  66604. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66605. */
  66606. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  66607. /**
  66608. * Shadow generator mode PCF: Percentage Closer Filtering
  66609. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  66610. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  66611. */
  66612. ShadowGenerator.FILTER_PCF = 6;
  66613. /**
  66614. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  66615. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  66616. * Contact Hardening
  66617. */
  66618. ShadowGenerator.FILTER_PCSS = 7;
  66619. /**
  66620. * Reserved for PCF and PCSS
  66621. * Highest Quality.
  66622. *
  66623. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  66624. *
  66625. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  66626. */
  66627. ShadowGenerator.QUALITY_HIGH = 0;
  66628. /**
  66629. * Reserved for PCF and PCSS
  66630. * Good tradeoff for quality/perf cross devices
  66631. *
  66632. * Execute PCF on a 3*3 kernel.
  66633. *
  66634. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  66635. */
  66636. ShadowGenerator.QUALITY_MEDIUM = 1;
  66637. /**
  66638. * Reserved for PCF and PCSS
  66639. * The lowest quality but the fastest.
  66640. *
  66641. * Execute PCF on a 1*1 kernel.
  66642. *
  66643. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  66644. */
  66645. ShadowGenerator.QUALITY_LOW = 2;
  66646. return ShadowGenerator;
  66647. }());
  66648. BABYLON.ShadowGenerator = ShadowGenerator;
  66649. })(BABYLON || (BABYLON = {}));
  66650. //# sourceMappingURL=babylon.shadowGenerator.js.map
  66651. var BABYLON;
  66652. (function (BABYLON) {
  66653. var DefaultLoadingScreen = /** @class */ (function () {
  66654. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  66655. if (_loadingText === void 0) { _loadingText = ""; }
  66656. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  66657. var _this = this;
  66658. this._renderingCanvas = _renderingCanvas;
  66659. this._loadingText = _loadingText;
  66660. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  66661. // Resize
  66662. this._resizeLoadingUI = function () {
  66663. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  66664. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  66665. if (!_this._loadingDiv) {
  66666. return;
  66667. }
  66668. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  66669. _this._loadingDiv.style.left = canvasRect.left + "px";
  66670. _this._loadingDiv.style.top = canvasRect.top + "px";
  66671. _this._loadingDiv.style.width = canvasRect.width + "px";
  66672. _this._loadingDiv.style.height = canvasRect.height + "px";
  66673. };
  66674. }
  66675. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  66676. if (this._loadingDiv) {
  66677. // Do not add a loading screen if there is already one
  66678. return;
  66679. }
  66680. this._loadingDiv = document.createElement("div");
  66681. this._loadingDiv.id = "babylonjsLoadingDiv";
  66682. this._loadingDiv.style.opacity = "0";
  66683. this._loadingDiv.style.transition = "opacity 1.5s ease";
  66684. this._loadingDiv.style.pointerEvents = "none";
  66685. // Loading text
  66686. this._loadingTextDiv = document.createElement("div");
  66687. this._loadingTextDiv.style.position = "absolute";
  66688. this._loadingTextDiv.style.left = "0";
  66689. this._loadingTextDiv.style.top = "50%";
  66690. this._loadingTextDiv.style.marginTop = "80px";
  66691. this._loadingTextDiv.style.width = "100%";
  66692. this._loadingTextDiv.style.height = "20px";
  66693. this._loadingTextDiv.style.fontFamily = "Arial";
  66694. this._loadingTextDiv.style.fontSize = "14px";
  66695. this._loadingTextDiv.style.color = "white";
  66696. this._loadingTextDiv.style.textAlign = "center";
  66697. this._loadingTextDiv.innerHTML = "Loading";
  66698. this._loadingDiv.appendChild(this._loadingTextDiv);
  66699. //set the predefined text
  66700. this._loadingTextDiv.innerHTML = this._loadingText;
  66701. // Generating keyframes
  66702. var style = document.createElement('style');
  66703. style.type = 'text/css';
  66704. 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 }";
  66705. style.innerHTML = keyFrames;
  66706. document.getElementsByTagName('head')[0].appendChild(style);
  66707. // Loading img
  66708. var imgBack = new Image();
  66709. 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";
  66710. imgBack.style.position = "absolute";
  66711. imgBack.style.left = "50%";
  66712. imgBack.style.top = "50%";
  66713. imgBack.style.marginLeft = "-60px";
  66714. imgBack.style.marginTop = "-60px";
  66715. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  66716. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  66717. imgBack.style.transformOrigin = "50% 50%";
  66718. imgBack.style.webkitTransformOrigin = "50% 50%";
  66719. this._loadingDiv.appendChild(imgBack);
  66720. this._resizeLoadingUI();
  66721. window.addEventListener("resize", this._resizeLoadingUI);
  66722. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  66723. document.body.appendChild(this._loadingDiv);
  66724. this._loadingDiv.style.opacity = "1";
  66725. };
  66726. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  66727. var _this = this;
  66728. if (!this._loadingDiv) {
  66729. return;
  66730. }
  66731. var onTransitionEnd = function () {
  66732. if (!_this._loadingDiv) {
  66733. return;
  66734. }
  66735. document.body.removeChild(_this._loadingDiv);
  66736. window.removeEventListener("resize", _this._resizeLoadingUI);
  66737. _this._loadingDiv = null;
  66738. };
  66739. this._loadingDiv.style.opacity = "0";
  66740. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  66741. };
  66742. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  66743. set: function (text) {
  66744. this._loadingText = text;
  66745. if (this._loadingTextDiv) {
  66746. this._loadingTextDiv.innerHTML = this._loadingText;
  66747. }
  66748. },
  66749. enumerable: true,
  66750. configurable: true
  66751. });
  66752. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  66753. get: function () {
  66754. return this._loadingDivBackgroundColor;
  66755. },
  66756. set: function (color) {
  66757. this._loadingDivBackgroundColor = color;
  66758. if (!this._loadingDiv) {
  66759. return;
  66760. }
  66761. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  66762. },
  66763. enumerable: true,
  66764. configurable: true
  66765. });
  66766. return DefaultLoadingScreen;
  66767. }());
  66768. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  66769. })(BABYLON || (BABYLON = {}));
  66770. //# sourceMappingURL=babylon.loadingScreen.js.map
  66771. var BABYLON;
  66772. (function (BABYLON) {
  66773. var SceneLoaderProgressEvent = /** @class */ (function () {
  66774. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  66775. this.lengthComputable = lengthComputable;
  66776. this.loaded = loaded;
  66777. this.total = total;
  66778. }
  66779. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  66780. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  66781. };
  66782. return SceneLoaderProgressEvent;
  66783. }());
  66784. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  66785. var SceneLoader = /** @class */ (function () {
  66786. function SceneLoader() {
  66787. }
  66788. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  66789. get: function () {
  66790. return 0;
  66791. },
  66792. enumerable: true,
  66793. configurable: true
  66794. });
  66795. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  66796. get: function () {
  66797. return 1;
  66798. },
  66799. enumerable: true,
  66800. configurable: true
  66801. });
  66802. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  66803. get: function () {
  66804. return 2;
  66805. },
  66806. enumerable: true,
  66807. configurable: true
  66808. });
  66809. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  66810. get: function () {
  66811. return 3;
  66812. },
  66813. enumerable: true,
  66814. configurable: true
  66815. });
  66816. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  66817. get: function () {
  66818. return SceneLoader._ForceFullSceneLoadingForIncremental;
  66819. },
  66820. set: function (value) {
  66821. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  66822. },
  66823. enumerable: true,
  66824. configurable: true
  66825. });
  66826. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  66827. get: function () {
  66828. return SceneLoader._ShowLoadingScreen;
  66829. },
  66830. set: function (value) {
  66831. SceneLoader._ShowLoadingScreen = value;
  66832. },
  66833. enumerable: true,
  66834. configurable: true
  66835. });
  66836. Object.defineProperty(SceneLoader, "loggingLevel", {
  66837. get: function () {
  66838. return SceneLoader._loggingLevel;
  66839. },
  66840. set: function (value) {
  66841. SceneLoader._loggingLevel = value;
  66842. },
  66843. enumerable: true,
  66844. configurable: true
  66845. });
  66846. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  66847. get: function () {
  66848. return SceneLoader._CleanBoneMatrixWeights;
  66849. },
  66850. set: function (value) {
  66851. SceneLoader._CleanBoneMatrixWeights = value;
  66852. },
  66853. enumerable: true,
  66854. configurable: true
  66855. });
  66856. SceneLoader._getDefaultPlugin = function () {
  66857. return SceneLoader._registeredPlugins[".babylon"];
  66858. };
  66859. SceneLoader._getPluginForExtension = function (extension) {
  66860. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  66861. if (registeredPlugin) {
  66862. return registeredPlugin;
  66863. }
  66864. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  66865. return SceneLoader._getDefaultPlugin();
  66866. };
  66867. SceneLoader._getPluginForDirectLoad = function (data) {
  66868. for (var extension in SceneLoader._registeredPlugins) {
  66869. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  66870. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  66871. return SceneLoader._registeredPlugins[extension];
  66872. }
  66873. }
  66874. return SceneLoader._getDefaultPlugin();
  66875. };
  66876. SceneLoader._getPluginForFilename = function (sceneFilename) {
  66877. if (sceneFilename.name) {
  66878. sceneFilename = sceneFilename.name;
  66879. }
  66880. var queryStringPosition = sceneFilename.indexOf("?");
  66881. if (queryStringPosition !== -1) {
  66882. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  66883. }
  66884. var dotPosition = sceneFilename.lastIndexOf(".");
  66885. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  66886. return SceneLoader._getPluginForExtension(extension);
  66887. };
  66888. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  66889. SceneLoader._getDirectLoad = function (sceneFilename) {
  66890. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  66891. return sceneFilename.substr(5);
  66892. }
  66893. return null;
  66894. };
  66895. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  66896. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  66897. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  66898. var plugin;
  66899. if (registeredPlugin.plugin.createPlugin) {
  66900. plugin = registeredPlugin.plugin.createPlugin();
  66901. }
  66902. else {
  66903. plugin = registeredPlugin.plugin;
  66904. }
  66905. var useArrayBuffer = registeredPlugin.isBinary;
  66906. var database;
  66907. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  66908. var dataCallback = function (data, responseURL) {
  66909. if (scene.isDisposed) {
  66910. onError("Scene has been disposed");
  66911. return;
  66912. }
  66913. scene.database = database;
  66914. onSuccess(plugin, data, responseURL);
  66915. };
  66916. var request = null;
  66917. var pluginDisposed = false;
  66918. var onDisposeObservable = plugin.onDisposeObservable;
  66919. if (onDisposeObservable) {
  66920. onDisposeObservable.add(function () {
  66921. pluginDisposed = true;
  66922. if (request) {
  66923. request.abort();
  66924. request = null;
  66925. }
  66926. onDispose();
  66927. });
  66928. }
  66929. var manifestChecked = function () {
  66930. if (pluginDisposed) {
  66931. return;
  66932. }
  66933. var url = rootUrl + sceneFilename;
  66934. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  66935. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  66936. } : undefined, database, useArrayBuffer, function (request, exception) {
  66937. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  66938. });
  66939. };
  66940. if (directLoad) {
  66941. dataCallback(directLoad);
  66942. return plugin;
  66943. }
  66944. if (rootUrl.indexOf("file:") === -1) {
  66945. var engine = scene.getEngine();
  66946. var canUseOfflineSupport = engine.enableOfflineSupport;
  66947. if (canUseOfflineSupport) {
  66948. // Also check for exceptions
  66949. var exceptionFound = false;
  66950. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  66951. var regex = _a[_i];
  66952. if (regex.test(rootUrl + sceneFilename)) {
  66953. exceptionFound = true;
  66954. break;
  66955. }
  66956. }
  66957. canUseOfflineSupport = !exceptionFound;
  66958. }
  66959. if (canUseOfflineSupport) {
  66960. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  66961. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked, engine.disableManifestCheck);
  66962. }
  66963. else {
  66964. manifestChecked();
  66965. }
  66966. }
  66967. // Loading file from disk via input file or drag'n'drop
  66968. else {
  66969. var fileOrString = sceneFilename;
  66970. if (fileOrString.name) { // File
  66971. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  66972. }
  66973. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  66974. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  66975. }
  66976. else {
  66977. onError("Unable to find file named " + sceneFilename);
  66978. }
  66979. }
  66980. return plugin;
  66981. };
  66982. // Public functions
  66983. SceneLoader.GetPluginForExtension = function (extension) {
  66984. return SceneLoader._getPluginForExtension(extension).plugin;
  66985. };
  66986. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  66987. return !!SceneLoader._registeredPlugins[extension];
  66988. };
  66989. SceneLoader.RegisterPlugin = function (plugin) {
  66990. if (typeof plugin.extensions === "string") {
  66991. var extension = plugin.extensions;
  66992. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  66993. plugin: plugin,
  66994. isBinary: false
  66995. };
  66996. }
  66997. else {
  66998. var extensions = plugin.extensions;
  66999. Object.keys(extensions).forEach(function (extension) {
  67000. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  67001. plugin: plugin,
  67002. isBinary: extensions[extension].isBinary
  67003. };
  67004. });
  67005. }
  67006. };
  67007. /**
  67008. * Import meshes into a scene
  67009. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  67010. * @param rootUrl a string that defines the root url for scene and resources
  67011. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67012. * @param scene the instance of BABYLON.Scene to append to
  67013. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  67014. * @param onProgress a callback with a progress event for each file being loaded
  67015. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67016. * @param pluginExtension the extension used to determine the plugin
  67017. * @returns The loaded plugin
  67018. */
  67019. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67020. if (onSuccess === void 0) { onSuccess = null; }
  67021. if (onProgress === void 0) { onProgress = null; }
  67022. if (onError === void 0) { onError = null; }
  67023. if (pluginExtension === void 0) { pluginExtension = null; }
  67024. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67025. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67026. return null;
  67027. }
  67028. var loadingToken = {};
  67029. scene._addPendingData(loadingToken);
  67030. var disposeHandler = function () {
  67031. scene._removePendingData(loadingToken);
  67032. };
  67033. var errorHandler = function (message, exception) {
  67034. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  67035. if (onError) {
  67036. onError(scene, errorMessage, exception);
  67037. }
  67038. else {
  67039. BABYLON.Tools.Error(errorMessage);
  67040. // should the exception be thrown?
  67041. }
  67042. disposeHandler();
  67043. };
  67044. var progressHandler = onProgress ? function (event) {
  67045. try {
  67046. onProgress(event);
  67047. }
  67048. catch (e) {
  67049. errorHandler("Error in onProgress callback", e);
  67050. }
  67051. } : undefined;
  67052. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  67053. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  67054. if (onSuccess) {
  67055. try {
  67056. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  67057. }
  67058. catch (e) {
  67059. errorHandler("Error in onSuccess callback", e);
  67060. }
  67061. }
  67062. scene._removePendingData(loadingToken);
  67063. };
  67064. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67065. if (plugin.rewriteRootURL) {
  67066. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  67067. }
  67068. if (sceneFilename === "") {
  67069. if (sceneFilename === "") {
  67070. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67071. }
  67072. }
  67073. if (plugin.importMesh) {
  67074. var syncedPlugin = plugin;
  67075. var meshes = new Array();
  67076. var particleSystems = new Array();
  67077. var skeletons = new Array();
  67078. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  67079. return;
  67080. }
  67081. scene.loadingPluginName = plugin.name;
  67082. successHandler(meshes, particleSystems, skeletons, []);
  67083. }
  67084. else {
  67085. var asyncedPlugin = plugin;
  67086. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  67087. scene.loadingPluginName = plugin.name;
  67088. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  67089. }).catch(function (error) {
  67090. errorHandler(error.message, error);
  67091. });
  67092. }
  67093. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67094. };
  67095. /**
  67096. * Import meshes into a scene
  67097. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  67098. * @param rootUrl a string that defines the root url for scene and resources
  67099. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67100. * @param scene the instance of BABYLON.Scene to append to
  67101. * @param onProgress a callback with a progress event for each file being loaded
  67102. * @param pluginExtension the extension used to determine the plugin
  67103. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  67104. */
  67105. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67106. if (onProgress === void 0) { onProgress = null; }
  67107. if (pluginExtension === void 0) { pluginExtension = null; }
  67108. return new Promise(function (resolve, reject) {
  67109. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  67110. resolve({
  67111. meshes: meshes,
  67112. particleSystems: particleSystems,
  67113. skeletons: skeletons,
  67114. animationGroups: animationGroups
  67115. });
  67116. }, onProgress, function (scene, message, exception) {
  67117. reject(exception || new Error(message));
  67118. }, pluginExtension);
  67119. });
  67120. };
  67121. /**
  67122. * Load a scene
  67123. * @param rootUrl a string that defines the root url for scene and resources
  67124. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67125. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67126. * @param onSuccess a callback with the scene when import succeeds
  67127. * @param onProgress a callback with a progress event for each file being loaded
  67128. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67129. * @param pluginExtension the extension used to determine the plugin
  67130. * @returns The loaded plugin
  67131. */
  67132. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  67133. if (onSuccess === void 0) { onSuccess = null; }
  67134. if (onProgress === void 0) { onProgress = null; }
  67135. if (onError === void 0) { onError = null; }
  67136. if (pluginExtension === void 0) { pluginExtension = null; }
  67137. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  67138. };
  67139. /**
  67140. * Load a scene
  67141. * @param rootUrl a string that defines the root url for scene and resources
  67142. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67143. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67144. * @param onProgress a callback with a progress event for each file being loaded
  67145. * @param pluginExtension the extension used to determine the plugin
  67146. * @returns The loaded scene
  67147. */
  67148. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  67149. if (onProgress === void 0) { onProgress = null; }
  67150. if (pluginExtension === void 0) { pluginExtension = null; }
  67151. return new Promise(function (resolve, reject) {
  67152. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  67153. resolve(scene);
  67154. }, onProgress, function (scene, message, exception) {
  67155. reject(exception || new Error(message));
  67156. }, pluginExtension);
  67157. });
  67158. };
  67159. /**
  67160. * Append a scene
  67161. * @param rootUrl a string that defines the root url for scene and resources
  67162. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67163. * @param scene is the instance of BABYLON.Scene to append to
  67164. * @param onSuccess a callback with the scene when import succeeds
  67165. * @param onProgress a callback with a progress event for each file being loaded
  67166. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67167. * @param pluginExtension the extension used to determine the plugin
  67168. * @returns The loaded plugin
  67169. */
  67170. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67171. if (onSuccess === void 0) { onSuccess = null; }
  67172. if (onProgress === void 0) { onProgress = null; }
  67173. if (onError === void 0) { onError = null; }
  67174. if (pluginExtension === void 0) { pluginExtension = null; }
  67175. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67176. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67177. return null;
  67178. }
  67179. if (SceneLoader.ShowLoadingScreen) {
  67180. scene.getEngine().displayLoadingUI();
  67181. }
  67182. var loadingToken = {};
  67183. scene._addPendingData(loadingToken);
  67184. var disposeHandler = function () {
  67185. scene._removePendingData(loadingToken);
  67186. scene.getEngine().hideLoadingUI();
  67187. };
  67188. var errorHandler = function (message, exception) {
  67189. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67190. if (onError) {
  67191. onError(scene, errorMessage, exception);
  67192. }
  67193. else {
  67194. BABYLON.Tools.Error(errorMessage);
  67195. // should the exception be thrown?
  67196. }
  67197. disposeHandler();
  67198. };
  67199. var progressHandler = onProgress ? function (event) {
  67200. try {
  67201. onProgress(event);
  67202. }
  67203. catch (e) {
  67204. errorHandler("Error in onProgress callback", e);
  67205. }
  67206. } : undefined;
  67207. var successHandler = function () {
  67208. if (onSuccess) {
  67209. try {
  67210. onSuccess(scene);
  67211. }
  67212. catch (e) {
  67213. errorHandler("Error in onSuccess callback", e);
  67214. }
  67215. }
  67216. scene._removePendingData(loadingToken);
  67217. };
  67218. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67219. if (sceneFilename === "") {
  67220. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67221. }
  67222. if (plugin.load) {
  67223. var syncedPlugin = plugin;
  67224. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  67225. return;
  67226. }
  67227. scene.loadingPluginName = plugin.name;
  67228. successHandler();
  67229. }
  67230. else {
  67231. var asyncedPlugin = plugin;
  67232. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  67233. scene.loadingPluginName = plugin.name;
  67234. successHandler();
  67235. }).catch(function (error) {
  67236. errorHandler(error.message, error);
  67237. });
  67238. }
  67239. if (SceneLoader.ShowLoadingScreen) {
  67240. scene.executeWhenReady(function () {
  67241. scene.getEngine().hideLoadingUI();
  67242. });
  67243. }
  67244. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67245. };
  67246. /**
  67247. * Append a scene
  67248. * @param rootUrl a string that defines the root url for scene and resources
  67249. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67250. * @param scene is the instance of BABYLON.Scene to append to
  67251. * @param onProgress a callback with a progress event for each file being loaded
  67252. * @param pluginExtension the extension used to determine the plugin
  67253. * @returns The given scene
  67254. */
  67255. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67256. if (onProgress === void 0) { onProgress = null; }
  67257. if (pluginExtension === void 0) { pluginExtension = null; }
  67258. return new Promise(function (resolve, reject) {
  67259. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  67260. resolve(scene);
  67261. }, onProgress, function (scene, message, exception) {
  67262. reject(exception || new Error(message));
  67263. }, pluginExtension);
  67264. });
  67265. };
  67266. /**
  67267. * Load a scene into an asset container
  67268. * @param rootUrl a string that defines the root url for scene and resources
  67269. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67270. * @param scene is the instance of BABYLON.Scene to append to
  67271. * @param onSuccess a callback with the scene when import succeeds
  67272. * @param onProgress a callback with a progress event for each file being loaded
  67273. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67274. * @param pluginExtension the extension used to determine the plugin
  67275. * @returns The loaded plugin
  67276. */
  67277. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67278. if (onSuccess === void 0) { onSuccess = null; }
  67279. if (onProgress === void 0) { onProgress = null; }
  67280. if (onError === void 0) { onError = null; }
  67281. if (pluginExtension === void 0) { pluginExtension = null; }
  67282. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67283. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67284. return null;
  67285. }
  67286. var loadingToken = {};
  67287. scene._addPendingData(loadingToken);
  67288. var disposeHandler = function () {
  67289. scene._removePendingData(loadingToken);
  67290. };
  67291. var errorHandler = function (message, exception) {
  67292. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67293. if (onError) {
  67294. onError(scene, errorMessage, exception);
  67295. }
  67296. else {
  67297. BABYLON.Tools.Error(errorMessage);
  67298. // should the exception be thrown?
  67299. }
  67300. disposeHandler();
  67301. };
  67302. var progressHandler = onProgress ? function (event) {
  67303. try {
  67304. onProgress(event);
  67305. }
  67306. catch (e) {
  67307. errorHandler("Error in onProgress callback", e);
  67308. }
  67309. } : undefined;
  67310. var successHandler = function (assets) {
  67311. if (onSuccess) {
  67312. try {
  67313. onSuccess(assets);
  67314. }
  67315. catch (e) {
  67316. errorHandler("Error in onSuccess callback", e);
  67317. }
  67318. }
  67319. scene._removePendingData(loadingToken);
  67320. };
  67321. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67322. if (plugin.loadAssetContainer) {
  67323. var syncedPlugin = plugin;
  67324. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  67325. if (!assetContainer) {
  67326. return;
  67327. }
  67328. scene.loadingPluginName = plugin.name;
  67329. successHandler(assetContainer);
  67330. }
  67331. else if (plugin.loadAssetContainerAsync) {
  67332. var asyncedPlugin = plugin;
  67333. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  67334. scene.loadingPluginName = plugin.name;
  67335. successHandler(assetContainer);
  67336. }).catch(function (error) {
  67337. errorHandler(error.message, error);
  67338. });
  67339. }
  67340. else {
  67341. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  67342. }
  67343. if (SceneLoader.ShowLoadingScreen) {
  67344. scene.executeWhenReady(function () {
  67345. scene.getEngine().hideLoadingUI();
  67346. });
  67347. }
  67348. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67349. };
  67350. /**
  67351. * Load a scene into an asset container
  67352. * @param rootUrl a string that defines the root url for scene and resources
  67353. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67354. * @param scene is the instance of BABYLON.Scene to append to
  67355. * @param onProgress a callback with a progress event for each file being loaded
  67356. * @param pluginExtension the extension used to determine the plugin
  67357. * @returns The loaded asset container
  67358. */
  67359. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67360. if (onProgress === void 0) { onProgress = null; }
  67361. if (pluginExtension === void 0) { pluginExtension = null; }
  67362. return new Promise(function (resolve, reject) {
  67363. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  67364. resolve(assetContainer);
  67365. }, onProgress, function (scene, message, exception) {
  67366. reject(exception || new Error(message));
  67367. }, pluginExtension);
  67368. });
  67369. };
  67370. // Flags
  67371. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  67372. SceneLoader._ShowLoadingScreen = true;
  67373. SceneLoader._CleanBoneMatrixWeights = false;
  67374. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  67375. // Members
  67376. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  67377. SceneLoader._registeredPlugins = {};
  67378. return SceneLoader;
  67379. }());
  67380. BABYLON.SceneLoader = SceneLoader;
  67381. ;
  67382. })(BABYLON || (BABYLON = {}));
  67383. //# sourceMappingURL=babylon.sceneLoader.js.map
  67384. var BABYLON;
  67385. (function (BABYLON) {
  67386. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  67387. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  67388. var parsedMaterial = parsedData.materials[index];
  67389. if (parsedMaterial.id === id) {
  67390. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  67391. }
  67392. }
  67393. return null;
  67394. };
  67395. var isDescendantOf = function (mesh, names, hierarchyIds) {
  67396. for (var i in names) {
  67397. if (mesh.name === names[i]) {
  67398. hierarchyIds.push(mesh.id);
  67399. return true;
  67400. }
  67401. }
  67402. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  67403. hierarchyIds.push(mesh.id);
  67404. return true;
  67405. }
  67406. return false;
  67407. };
  67408. var logOperation = function (operation, producer) {
  67409. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  67410. };
  67411. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  67412. if (addToScene === void 0) { addToScene = false; }
  67413. var container = new BABYLON.AssetContainer(scene);
  67414. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67415. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67416. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67417. // and avoid problems with multiple concurrent .babylon loads.
  67418. var log = "importScene has failed JSON parse";
  67419. try {
  67420. var parsedData = JSON.parse(data);
  67421. log = "";
  67422. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  67423. var index;
  67424. var cache;
  67425. // Lights
  67426. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  67427. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  67428. var parsedLight = parsedData.lights[index];
  67429. var light = BABYLON.Light.Parse(parsedLight, scene);
  67430. if (light) {
  67431. container.lights.push(light);
  67432. log += (index === 0 ? "\n\tLights:" : "");
  67433. log += "\n\t\t" + light.toString(fullDetails);
  67434. }
  67435. }
  67436. }
  67437. // Animations
  67438. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  67439. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  67440. var parsedAnimation = parsedData.animations[index];
  67441. var animation = BABYLON.Animation.Parse(parsedAnimation);
  67442. scene.animations.push(animation);
  67443. container.animations.push(animation);
  67444. log += (index === 0 ? "\n\tAnimations:" : "");
  67445. log += "\n\t\t" + animation.toString(fullDetails);
  67446. }
  67447. }
  67448. // Materials
  67449. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  67450. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  67451. var parsedMaterial = parsedData.materials[index];
  67452. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  67453. container.materials.push(mat);
  67454. log += (index === 0 ? "\n\tMaterials:" : "");
  67455. log += "\n\t\t" + mat.toString(fullDetails);
  67456. }
  67457. }
  67458. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  67459. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  67460. var parsedMultiMaterial = parsedData.multiMaterials[index];
  67461. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  67462. container.multiMaterials.push(mmat);
  67463. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  67464. log += "\n\t\t" + mmat.toString(fullDetails);
  67465. }
  67466. }
  67467. // Morph targets
  67468. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  67469. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  67470. var managerData = _a[_i];
  67471. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  67472. }
  67473. }
  67474. // Skeletons
  67475. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  67476. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  67477. var parsedSkeleton = parsedData.skeletons[index];
  67478. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  67479. container.skeletons.push(skeleton);
  67480. log += (index === 0 ? "\n\tSkeletons:" : "");
  67481. log += "\n\t\t" + skeleton.toString(fullDetails);
  67482. }
  67483. }
  67484. // Geometries
  67485. var geometries = parsedData.geometries;
  67486. if (geometries !== undefined && geometries !== null) {
  67487. var addedGeometry = new Array();
  67488. // Boxes
  67489. var boxes = geometries.boxes;
  67490. if (boxes !== undefined && boxes !== null) {
  67491. for (index = 0, cache = boxes.length; index < cache; index++) {
  67492. var parsedBox = boxes[index];
  67493. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  67494. }
  67495. }
  67496. // Spheres
  67497. var spheres = geometries.spheres;
  67498. if (spheres !== undefined && spheres !== null) {
  67499. for (index = 0, cache = spheres.length; index < cache; index++) {
  67500. var parsedSphere = spheres[index];
  67501. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  67502. }
  67503. }
  67504. // Cylinders
  67505. var cylinders = geometries.cylinders;
  67506. if (cylinders !== undefined && cylinders !== null) {
  67507. for (index = 0, cache = cylinders.length; index < cache; index++) {
  67508. var parsedCylinder = cylinders[index];
  67509. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  67510. }
  67511. }
  67512. // Toruses
  67513. var toruses = geometries.toruses;
  67514. if (toruses !== undefined && toruses !== null) {
  67515. for (index = 0, cache = toruses.length; index < cache; index++) {
  67516. var parsedTorus = toruses[index];
  67517. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  67518. }
  67519. }
  67520. // Grounds
  67521. var grounds = geometries.grounds;
  67522. if (grounds !== undefined && grounds !== null) {
  67523. for (index = 0, cache = grounds.length; index < cache; index++) {
  67524. var parsedGround = grounds[index];
  67525. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  67526. }
  67527. }
  67528. // Planes
  67529. var planes = geometries.planes;
  67530. if (planes !== undefined && planes !== null) {
  67531. for (index = 0, cache = planes.length; index < cache; index++) {
  67532. var parsedPlane = planes[index];
  67533. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  67534. }
  67535. }
  67536. // TorusKnots
  67537. var torusKnots = geometries.torusKnots;
  67538. if (torusKnots !== undefined && torusKnots !== null) {
  67539. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  67540. var parsedTorusKnot = torusKnots[index];
  67541. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  67542. }
  67543. }
  67544. // VertexData
  67545. var vertexData = geometries.vertexData;
  67546. if (vertexData !== undefined && vertexData !== null) {
  67547. for (index = 0, cache = vertexData.length; index < cache; index++) {
  67548. var parsedVertexData = vertexData[index];
  67549. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  67550. }
  67551. }
  67552. addedGeometry.forEach(function (g) {
  67553. if (g) {
  67554. container.geometries.push(g);
  67555. }
  67556. });
  67557. }
  67558. // Transform nodes
  67559. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  67560. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  67561. var parsedTransformNode = parsedData.transformNodes[index];
  67562. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  67563. container.transformNodes.push(node);
  67564. }
  67565. }
  67566. // Meshes
  67567. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  67568. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  67569. var parsedMesh = parsedData.meshes[index];
  67570. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  67571. container.meshes.push(mesh);
  67572. log += (index === 0 ? "\n\tMeshes:" : "");
  67573. log += "\n\t\t" + mesh.toString(fullDetails);
  67574. }
  67575. }
  67576. // Cameras
  67577. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  67578. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  67579. var parsedCamera = parsedData.cameras[index];
  67580. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  67581. container.cameras.push(camera);
  67582. log += (index === 0 ? "\n\tCameras:" : "");
  67583. log += "\n\t\t" + camera.toString(fullDetails);
  67584. }
  67585. }
  67586. // Browsing all the graph to connect the dots
  67587. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  67588. var camera = scene.cameras[index];
  67589. if (camera._waitingParentId) {
  67590. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  67591. camera._waitingParentId = null;
  67592. }
  67593. }
  67594. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  67595. var light_1 = scene.lights[index];
  67596. if (light_1 && light_1._waitingParentId) {
  67597. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  67598. light_1._waitingParentId = null;
  67599. }
  67600. }
  67601. // Sounds
  67602. // TODO: add sound
  67603. var loadedSounds = [];
  67604. var loadedSound;
  67605. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  67606. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  67607. var parsedSound = parsedData.sounds[index];
  67608. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  67609. if (!parsedSound.url)
  67610. parsedSound.url = parsedSound.name;
  67611. if (!loadedSounds[parsedSound.url]) {
  67612. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  67613. loadedSounds[parsedSound.url] = loadedSound;
  67614. container.sounds.push(loadedSound);
  67615. }
  67616. else {
  67617. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  67618. }
  67619. }
  67620. else {
  67621. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  67622. }
  67623. }
  67624. }
  67625. loadedSounds = [];
  67626. // Connect parents & children and parse actions
  67627. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  67628. var transformNode = scene.transformNodes[index];
  67629. if (transformNode._waitingParentId) {
  67630. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  67631. transformNode._waitingParentId = null;
  67632. }
  67633. }
  67634. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67635. var mesh = scene.meshes[index];
  67636. if (mesh._waitingParentId) {
  67637. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  67638. mesh._waitingParentId = null;
  67639. }
  67640. if (mesh._waitingActions) {
  67641. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  67642. mesh._waitingActions = null;
  67643. }
  67644. }
  67645. // freeze world matrix application
  67646. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67647. var currentMesh = scene.meshes[index];
  67648. if (currentMesh._waitingFreezeWorldMatrix) {
  67649. currentMesh.freezeWorldMatrix();
  67650. currentMesh._waitingFreezeWorldMatrix = null;
  67651. }
  67652. else {
  67653. currentMesh.computeWorldMatrix(true);
  67654. }
  67655. }
  67656. // Particles Systems
  67657. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  67658. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  67659. var parsedParticleSystem = parsedData.particleSystems[index];
  67660. if (parsedParticleSystem.activeParticleCount) {
  67661. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  67662. container.particleSystems.push(ps);
  67663. }
  67664. else {
  67665. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  67666. container.particleSystems.push(ps);
  67667. }
  67668. }
  67669. }
  67670. // Lens flares
  67671. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  67672. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  67673. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  67674. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  67675. container.lensFlareSystems.push(lf);
  67676. }
  67677. }
  67678. // Shadows
  67679. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  67680. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  67681. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  67682. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  67683. container.shadowGenerators.push(sg);
  67684. }
  67685. }
  67686. // Lights exclusions / inclusions
  67687. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  67688. var light_2 = scene.lights[index];
  67689. // Excluded check
  67690. if (light_2._excludedMeshesIds.length > 0) {
  67691. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  67692. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  67693. if (excludedMesh) {
  67694. light_2.excludedMeshes.push(excludedMesh);
  67695. }
  67696. }
  67697. light_2._excludedMeshesIds = [];
  67698. }
  67699. // Included check
  67700. if (light_2._includedOnlyMeshesIds.length > 0) {
  67701. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  67702. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  67703. if (includedOnlyMesh) {
  67704. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  67705. }
  67706. }
  67707. light_2._includedOnlyMeshesIds = [];
  67708. }
  67709. }
  67710. // Effect layers
  67711. if (parsedData.effectLayers) {
  67712. for (index = 0; index < parsedData.effectLayers.length; index++) {
  67713. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  67714. container.effectLayers.push(effectLayer);
  67715. }
  67716. }
  67717. // Actions (scene)
  67718. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  67719. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  67720. }
  67721. if (!addToScene) {
  67722. container.removeAllFromScene();
  67723. }
  67724. }
  67725. catch (err) {
  67726. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  67727. if (onError) {
  67728. onError(msg, err);
  67729. }
  67730. else {
  67731. BABYLON.Tools.Log(msg);
  67732. throw err;
  67733. }
  67734. }
  67735. finally {
  67736. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  67737. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  67738. }
  67739. }
  67740. return container;
  67741. };
  67742. BABYLON.SceneLoader.RegisterPlugin({
  67743. name: "babylon.js",
  67744. extensions: ".babylon",
  67745. canDirectLoad: function (data) {
  67746. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  67747. return true;
  67748. }
  67749. return false;
  67750. },
  67751. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  67752. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67753. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67754. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67755. // and avoid problems with multiple concurrent .babylon loads.
  67756. var log = "importMesh has failed JSON parse";
  67757. try {
  67758. var parsedData = JSON.parse(data);
  67759. log = "";
  67760. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  67761. if (!meshesNames) {
  67762. meshesNames = null;
  67763. }
  67764. else if (!Array.isArray(meshesNames)) {
  67765. meshesNames = [meshesNames];
  67766. }
  67767. var hierarchyIds = new Array();
  67768. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  67769. var loadedSkeletonsIds = [];
  67770. var loadedMaterialsIds = [];
  67771. var index;
  67772. var cache;
  67773. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  67774. var parsedMesh = parsedData.meshes[index];
  67775. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  67776. if (meshesNames !== null) {
  67777. // Remove found mesh name from list.
  67778. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  67779. }
  67780. //Geometry?
  67781. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  67782. //does the file contain geometries?
  67783. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  67784. //find the correct geometry and add it to the scene
  67785. var found = false;
  67786. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  67787. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  67788. return;
  67789. }
  67790. else {
  67791. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  67792. if (parsedGeometryData.id === parsedMesh.geometryId) {
  67793. switch (geometryType) {
  67794. case "boxes":
  67795. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  67796. break;
  67797. case "spheres":
  67798. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  67799. break;
  67800. case "cylinders":
  67801. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  67802. break;
  67803. case "toruses":
  67804. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  67805. break;
  67806. case "grounds":
  67807. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  67808. break;
  67809. case "planes":
  67810. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  67811. break;
  67812. case "torusKnots":
  67813. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  67814. break;
  67815. case "vertexData":
  67816. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  67817. break;
  67818. }
  67819. found = true;
  67820. }
  67821. });
  67822. }
  67823. });
  67824. if (found === false) {
  67825. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  67826. }
  67827. }
  67828. }
  67829. // Material ?
  67830. if (parsedMesh.materialId) {
  67831. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  67832. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  67833. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  67834. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  67835. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  67836. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  67837. var subMatId = parsedMultiMaterial.materials[matIndex];
  67838. loadedMaterialsIds.push(subMatId);
  67839. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  67840. if (mat) {
  67841. log += "\n\tMaterial " + mat.toString(fullDetails);
  67842. }
  67843. }
  67844. loadedMaterialsIds.push(parsedMultiMaterial.id);
  67845. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  67846. if (mmat) {
  67847. materialFound = true;
  67848. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  67849. }
  67850. break;
  67851. }
  67852. }
  67853. }
  67854. if (materialFound === false) {
  67855. loadedMaterialsIds.push(parsedMesh.materialId);
  67856. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  67857. if (!mat) {
  67858. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  67859. }
  67860. else {
  67861. log += "\n\tMaterial " + mat.toString(fullDetails);
  67862. }
  67863. }
  67864. }
  67865. // Skeleton ?
  67866. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  67867. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  67868. if (skeletonAlreadyLoaded === false) {
  67869. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  67870. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  67871. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  67872. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  67873. skeletons.push(skeleton);
  67874. loadedSkeletonsIds.push(parsedSkeleton.id);
  67875. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  67876. }
  67877. }
  67878. }
  67879. }
  67880. // Morph targets ?
  67881. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  67882. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  67883. var managerData = _a[_i];
  67884. BABYLON.MorphTargetManager.Parse(managerData, scene);
  67885. }
  67886. }
  67887. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  67888. meshes.push(mesh);
  67889. log += "\n\tMesh " + mesh.toString(fullDetails);
  67890. }
  67891. }
  67892. // Connecting parents
  67893. var currentMesh;
  67894. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67895. currentMesh = scene.meshes[index];
  67896. if (currentMesh._waitingParentId) {
  67897. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  67898. currentMesh._waitingParentId = null;
  67899. }
  67900. }
  67901. // freeze and compute world matrix application
  67902. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67903. currentMesh = scene.meshes[index];
  67904. if (currentMesh._waitingFreezeWorldMatrix) {
  67905. currentMesh.freezeWorldMatrix();
  67906. currentMesh._waitingFreezeWorldMatrix = null;
  67907. }
  67908. else {
  67909. currentMesh.computeWorldMatrix(true);
  67910. }
  67911. }
  67912. }
  67913. // Particles
  67914. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  67915. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  67916. var parsedParticleSystem = parsedData.particleSystems[index];
  67917. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  67918. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  67919. }
  67920. }
  67921. }
  67922. return true;
  67923. }
  67924. catch (err) {
  67925. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  67926. if (onError) {
  67927. onError(msg, err);
  67928. }
  67929. else {
  67930. BABYLON.Tools.Log(msg);
  67931. throw err;
  67932. }
  67933. }
  67934. finally {
  67935. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  67936. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  67937. }
  67938. }
  67939. return false;
  67940. },
  67941. load: function (scene, data, rootUrl, onError) {
  67942. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67943. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67944. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67945. // and avoid problems with multiple concurrent .babylon loads.
  67946. var log = "importScene has failed JSON parse";
  67947. try {
  67948. var parsedData = JSON.parse(data);
  67949. log = "";
  67950. // Scene
  67951. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  67952. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  67953. }
  67954. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  67955. scene.autoClear = parsedData.autoClear;
  67956. }
  67957. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  67958. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  67959. }
  67960. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  67961. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  67962. }
  67963. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  67964. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  67965. }
  67966. // Fog
  67967. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  67968. scene.fogMode = parsedData.fogMode;
  67969. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  67970. scene.fogStart = parsedData.fogStart;
  67971. scene.fogEnd = parsedData.fogEnd;
  67972. scene.fogDensity = parsedData.fogDensity;
  67973. log += "\tFog mode for scene: ";
  67974. switch (scene.fogMode) {
  67975. // getters not compiling, so using hardcoded
  67976. case 1:
  67977. log += "exp\n";
  67978. break;
  67979. case 2:
  67980. log += "exp2\n";
  67981. break;
  67982. case 3:
  67983. log += "linear\n";
  67984. break;
  67985. }
  67986. }
  67987. //Physics
  67988. if (parsedData.physicsEnabled) {
  67989. var physicsPlugin;
  67990. if (parsedData.physicsEngine === "cannon") {
  67991. physicsPlugin = new BABYLON.CannonJSPlugin();
  67992. }
  67993. else if (parsedData.physicsEngine === "oimo") {
  67994. physicsPlugin = new BABYLON.OimoJSPlugin();
  67995. }
  67996. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  67997. //else - default engine, which is currently oimo
  67998. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  67999. scene.enablePhysics(physicsGravity, physicsPlugin);
  68000. }
  68001. // Metadata
  68002. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  68003. scene.metadata = parsedData.metadata;
  68004. }
  68005. //collisions, if defined. otherwise, default is true
  68006. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  68007. scene.collisionsEnabled = parsedData.collisionsEnabled;
  68008. }
  68009. scene.workerCollisions = !!parsedData.workerCollisions;
  68010. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  68011. if (!container) {
  68012. return false;
  68013. }
  68014. if (parsedData.autoAnimate) {
  68015. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  68016. }
  68017. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  68018. scene.setActiveCameraByID(parsedData.activeCameraID);
  68019. }
  68020. // Environment texture
  68021. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  68022. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  68023. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  68024. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  68025. if (parsedData.environmentTextureRotationY) {
  68026. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  68027. }
  68028. scene.environmentTexture = hdrTexture;
  68029. }
  68030. else {
  68031. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  68032. if (parsedData.environmentTextureRotationY) {
  68033. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  68034. }
  68035. scene.environmentTexture = cubeTexture;
  68036. }
  68037. if (parsedData.createDefaultSkybox === true) {
  68038. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  68039. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  68040. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  68041. }
  68042. }
  68043. // Finish
  68044. return true;
  68045. }
  68046. catch (err) {
  68047. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  68048. if (onError) {
  68049. onError(msg, err);
  68050. }
  68051. else {
  68052. BABYLON.Tools.Log(msg);
  68053. throw err;
  68054. }
  68055. }
  68056. finally {
  68057. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68058. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68059. }
  68060. }
  68061. return false;
  68062. },
  68063. loadAssetContainer: function (scene, data, rootUrl, onError) {
  68064. var container = loadAssetContainer(scene, data, rootUrl, onError);
  68065. return container;
  68066. }
  68067. });
  68068. })(BABYLON || (BABYLON = {}));
  68069. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  68070. var BABYLON;
  68071. (function (BABYLON) {
  68072. var FilesInput = /** @class */ (function () {
  68073. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  68074. this.onProcessFileCallback = function () { return true; };
  68075. this._engine = engine;
  68076. this._currentScene = scene;
  68077. this._sceneLoadedCallback = sceneLoadedCallback;
  68078. this._progressCallback = progressCallback;
  68079. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  68080. this._textureLoadingCallback = textureLoadingCallback;
  68081. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  68082. this._onReloadCallback = onReloadCallback;
  68083. this._errorCallback = errorCallback;
  68084. }
  68085. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  68086. var _this = this;
  68087. if (elementToMonitor) {
  68088. this._elementToMonitor = elementToMonitor;
  68089. this._dragEnterHandler = function (e) { _this.drag(e); };
  68090. this._dragOverHandler = function (e) { _this.drag(e); };
  68091. this._dropHandler = function (e) { _this.drop(e); };
  68092. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  68093. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  68094. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  68095. }
  68096. };
  68097. FilesInput.prototype.dispose = function () {
  68098. if (!this._elementToMonitor) {
  68099. return;
  68100. }
  68101. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  68102. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  68103. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  68104. };
  68105. FilesInput.prototype.renderFunction = function () {
  68106. if (this._additionalRenderLoopLogicCallback) {
  68107. this._additionalRenderLoopLogicCallback();
  68108. }
  68109. if (this._currentScene) {
  68110. if (this._textureLoadingCallback) {
  68111. var remaining = this._currentScene.getWaitingItemsCount();
  68112. if (remaining > 0) {
  68113. this._textureLoadingCallback(remaining);
  68114. }
  68115. }
  68116. this._currentScene.render();
  68117. }
  68118. };
  68119. FilesInput.prototype.drag = function (e) {
  68120. e.stopPropagation();
  68121. e.preventDefault();
  68122. };
  68123. FilesInput.prototype.drop = function (eventDrop) {
  68124. eventDrop.stopPropagation();
  68125. eventDrop.preventDefault();
  68126. this.loadFiles(eventDrop);
  68127. };
  68128. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  68129. var _this = this;
  68130. var reader = folder.createReader();
  68131. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  68132. reader.readEntries(function (entries) {
  68133. remaining.count += entries.length;
  68134. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  68135. var entry = entries_1[_i];
  68136. if (entry.isFile) {
  68137. entry.file(function (file) {
  68138. file.correctName = relativePath + file.name;
  68139. files.push(file);
  68140. if (--remaining.count === 0) {
  68141. callback();
  68142. }
  68143. });
  68144. }
  68145. else if (entry.isDirectory) {
  68146. _this._traverseFolder(entry, files, remaining, callback);
  68147. }
  68148. }
  68149. if (--remaining.count) {
  68150. callback();
  68151. }
  68152. });
  68153. };
  68154. FilesInput.prototype._processFiles = function (files) {
  68155. for (var i = 0; i < files.length; i++) {
  68156. var name = files[i].correctName.toLowerCase();
  68157. var extension = name.split('.').pop();
  68158. if (!this.onProcessFileCallback(files[i], name, extension)) {
  68159. continue;
  68160. }
  68161. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  68162. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  68163. this._sceneFileToLoad = files[i];
  68164. }
  68165. else {
  68166. FilesInput.FilesToLoad[name] = files[i];
  68167. }
  68168. }
  68169. };
  68170. FilesInput.prototype.loadFiles = function (event) {
  68171. var _this = this;
  68172. if (this._startingProcessingFilesCallback)
  68173. this._startingProcessingFilesCallback();
  68174. // Handling data transfer via drag'n'drop
  68175. if (event && event.dataTransfer && event.dataTransfer.files) {
  68176. this._filesToLoad = event.dataTransfer.files;
  68177. }
  68178. // Handling files from input files
  68179. if (event && event.target && event.target.files) {
  68180. this._filesToLoad = event.target.files;
  68181. }
  68182. if (this._filesToLoad && this._filesToLoad.length > 0) {
  68183. var files_1 = new Array();
  68184. var folders = [];
  68185. var items = event.dataTransfer ? event.dataTransfer.items : null;
  68186. for (var i = 0; i < this._filesToLoad.length; i++) {
  68187. var fileToLoad = this._filesToLoad[i];
  68188. var name_1 = fileToLoad.name.toLowerCase();
  68189. var entry = void 0;
  68190. fileToLoad.correctName = name_1;
  68191. if (items) {
  68192. var item = items[i];
  68193. if (item.getAsEntry) {
  68194. entry = item.getAsEntry();
  68195. }
  68196. else if (item.webkitGetAsEntry) {
  68197. entry = item.webkitGetAsEntry();
  68198. }
  68199. }
  68200. if (!entry) {
  68201. files_1.push(fileToLoad);
  68202. }
  68203. else {
  68204. if (entry.isDirectory) {
  68205. folders.push(entry);
  68206. }
  68207. else {
  68208. files_1.push(fileToLoad);
  68209. }
  68210. }
  68211. }
  68212. if (folders.length === 0) {
  68213. this._processFiles(files_1);
  68214. this._processReload();
  68215. }
  68216. else {
  68217. var remaining = { count: folders.length };
  68218. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  68219. var folder = folders_1[_i];
  68220. this._traverseFolder(folder, files_1, remaining, function () {
  68221. _this._processFiles(files_1);
  68222. if (remaining.count === 0) {
  68223. _this._processReload();
  68224. }
  68225. });
  68226. }
  68227. }
  68228. }
  68229. };
  68230. FilesInput.prototype._processReload = function () {
  68231. if (this._onReloadCallback) {
  68232. this._onReloadCallback(this._sceneFileToLoad);
  68233. }
  68234. else {
  68235. this.reload();
  68236. }
  68237. };
  68238. FilesInput.prototype.reload = function () {
  68239. var _this = this;
  68240. // If a scene file has been provided
  68241. if (this._sceneFileToLoad) {
  68242. if (this._currentScene) {
  68243. if (BABYLON.Tools.errorsCount > 0) {
  68244. BABYLON.Tools.ClearLogCache();
  68245. }
  68246. this._engine.stopRenderLoop();
  68247. this._currentScene.dispose();
  68248. }
  68249. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  68250. if (_this._progressCallback) {
  68251. _this._progressCallback(progress);
  68252. }
  68253. }).then(function (scene) {
  68254. _this._currentScene = scene;
  68255. if (_this._sceneLoadedCallback) {
  68256. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  68257. }
  68258. // Wait for textures and shaders to be ready
  68259. _this._currentScene.executeWhenReady(function () {
  68260. _this._engine.runRenderLoop(function () {
  68261. _this.renderFunction();
  68262. });
  68263. });
  68264. }).catch(function (error) {
  68265. if (_this._errorCallback) {
  68266. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  68267. }
  68268. });
  68269. }
  68270. else {
  68271. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  68272. }
  68273. };
  68274. FilesInput.FilesToLoad = {};
  68275. return FilesInput;
  68276. }());
  68277. BABYLON.FilesInput = FilesInput;
  68278. })(BABYLON || (BABYLON = {}));
  68279. //# sourceMappingURL=babylon.filesInput.js.map
  68280. var BABYLON;
  68281. (function (BABYLON) {
  68282. /**
  68283. * This class implement a typical dictionary using a string as key and the generic type T as value.
  68284. * The underlying implementation relies on an associative array to ensure the best performances.
  68285. * The value can be anything including 'null' but except 'undefined'
  68286. */
  68287. var StringDictionary = /** @class */ (function () {
  68288. function StringDictionary() {
  68289. this._count = 0;
  68290. this._data = {};
  68291. }
  68292. /**
  68293. * This will clear this dictionary and copy the content from the 'source' one.
  68294. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  68295. * @param source the dictionary to take the content from and copy to this dictionary
  68296. */
  68297. StringDictionary.prototype.copyFrom = function (source) {
  68298. var _this = this;
  68299. this.clear();
  68300. source.forEach(function (t, v) { return _this.add(t, v); });
  68301. };
  68302. /**
  68303. * Get a value based from its key
  68304. * @param key the given key to get the matching value from
  68305. * @return the value if found, otherwise undefined is returned
  68306. */
  68307. StringDictionary.prototype.get = function (key) {
  68308. var val = this._data[key];
  68309. if (val !== undefined) {
  68310. return val;
  68311. }
  68312. return undefined;
  68313. };
  68314. /**
  68315. * Get a value from its key or add it if it doesn't exist.
  68316. * This method will ensure you that a given key/data will be present in the dictionary.
  68317. * @param key the given key to get the matching value from
  68318. * @param factory the factory that will create the value if the key is not present in the dictionary.
  68319. * The factory will only be invoked if there's no data for the given key.
  68320. * @return the value corresponding to the key.
  68321. */
  68322. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  68323. var val = this.get(key);
  68324. if (val !== undefined) {
  68325. return val;
  68326. }
  68327. val = factory(key);
  68328. if (val) {
  68329. this.add(key, val);
  68330. }
  68331. return val;
  68332. };
  68333. /**
  68334. * Get a value from its key if present in the dictionary otherwise add it
  68335. * @param key the key to get the value from
  68336. * @param val if there's no such key/value pair in the dictionary add it with this value
  68337. * @return the value corresponding to the key
  68338. */
  68339. StringDictionary.prototype.getOrAdd = function (key, val) {
  68340. var curVal = this.get(key);
  68341. if (curVal !== undefined) {
  68342. return curVal;
  68343. }
  68344. this.add(key, val);
  68345. return val;
  68346. };
  68347. /**
  68348. * Check if there's a given key in the dictionary
  68349. * @param key the key to check for
  68350. * @return true if the key is present, false otherwise
  68351. */
  68352. StringDictionary.prototype.contains = function (key) {
  68353. return this._data[key] !== undefined;
  68354. };
  68355. /**
  68356. * Add a new key and its corresponding value
  68357. * @param key the key to add
  68358. * @param value the value corresponding to the key
  68359. * @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
  68360. */
  68361. StringDictionary.prototype.add = function (key, value) {
  68362. if (this._data[key] !== undefined) {
  68363. return false;
  68364. }
  68365. this._data[key] = value;
  68366. ++this._count;
  68367. return true;
  68368. };
  68369. StringDictionary.prototype.set = function (key, value) {
  68370. if (this._data[key] === undefined) {
  68371. return false;
  68372. }
  68373. this._data[key] = value;
  68374. return true;
  68375. };
  68376. /**
  68377. * Get the element of the given key and remove it from the dictionary
  68378. * @param key
  68379. */
  68380. StringDictionary.prototype.getAndRemove = function (key) {
  68381. var val = this.get(key);
  68382. if (val !== undefined) {
  68383. delete this._data[key];
  68384. --this._count;
  68385. return val;
  68386. }
  68387. return null;
  68388. };
  68389. /**
  68390. * Remove a key/value from the dictionary.
  68391. * @param key the key to remove
  68392. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  68393. */
  68394. StringDictionary.prototype.remove = function (key) {
  68395. if (this.contains(key)) {
  68396. delete this._data[key];
  68397. --this._count;
  68398. return true;
  68399. }
  68400. return false;
  68401. };
  68402. /**
  68403. * Clear the whole content of the dictionary
  68404. */
  68405. StringDictionary.prototype.clear = function () {
  68406. this._data = {};
  68407. this._count = 0;
  68408. };
  68409. Object.defineProperty(StringDictionary.prototype, "count", {
  68410. get: function () {
  68411. return this._count;
  68412. },
  68413. enumerable: true,
  68414. configurable: true
  68415. });
  68416. /**
  68417. * Execute a callback on each key/val of the dictionary.
  68418. * Note that you can remove any element in this dictionary in the callback implementation
  68419. * @param callback the callback to execute on a given key/value pair
  68420. */
  68421. StringDictionary.prototype.forEach = function (callback) {
  68422. for (var cur in this._data) {
  68423. var val = this._data[cur];
  68424. callback(cur, val);
  68425. }
  68426. };
  68427. /**
  68428. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  68429. * If the callback returns null or undefined the method will iterate to the next key/value pair
  68430. * Note that you can remove any element in this dictionary in the callback implementation
  68431. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  68432. */
  68433. StringDictionary.prototype.first = function (callback) {
  68434. for (var cur in this._data) {
  68435. var val = this._data[cur];
  68436. var res = callback(cur, val);
  68437. if (res) {
  68438. return res;
  68439. }
  68440. }
  68441. return null;
  68442. };
  68443. return StringDictionary;
  68444. }());
  68445. BABYLON.StringDictionary = StringDictionary;
  68446. })(BABYLON || (BABYLON = {}));
  68447. //# sourceMappingURL=babylon.stringDictionary.js.map
  68448. var BABYLON;
  68449. (function (BABYLON) {
  68450. var Tags = /** @class */ (function () {
  68451. function Tags() {
  68452. }
  68453. Tags.EnableFor = function (obj) {
  68454. obj._tags = obj._tags || {};
  68455. obj.hasTags = function () {
  68456. return Tags.HasTags(obj);
  68457. };
  68458. obj.addTags = function (tagsString) {
  68459. return Tags.AddTagsTo(obj, tagsString);
  68460. };
  68461. obj.removeTags = function (tagsString) {
  68462. return Tags.RemoveTagsFrom(obj, tagsString);
  68463. };
  68464. obj.matchesTagsQuery = function (tagsQuery) {
  68465. return Tags.MatchesQuery(obj, tagsQuery);
  68466. };
  68467. };
  68468. Tags.DisableFor = function (obj) {
  68469. delete obj._tags;
  68470. delete obj.hasTags;
  68471. delete obj.addTags;
  68472. delete obj.removeTags;
  68473. delete obj.matchesTagsQuery;
  68474. };
  68475. Tags.HasTags = function (obj) {
  68476. if (!obj._tags) {
  68477. return false;
  68478. }
  68479. return !BABYLON.Tools.IsEmpty(obj._tags);
  68480. };
  68481. Tags.GetTags = function (obj, asString) {
  68482. if (asString === void 0) { asString = true; }
  68483. if (!obj._tags) {
  68484. return null;
  68485. }
  68486. if (asString) {
  68487. var tagsArray = [];
  68488. for (var tag in obj._tags) {
  68489. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  68490. tagsArray.push(tag);
  68491. }
  68492. }
  68493. return tagsArray.join(" ");
  68494. }
  68495. else {
  68496. return obj._tags;
  68497. }
  68498. };
  68499. // the tags 'true' and 'false' are reserved and cannot be used as tags
  68500. // a tag cannot start with '||', '&&', and '!'
  68501. // it cannot contain whitespaces
  68502. Tags.AddTagsTo = function (obj, tagsString) {
  68503. if (!tagsString) {
  68504. return;
  68505. }
  68506. if (typeof tagsString !== "string") {
  68507. return;
  68508. }
  68509. var tags = tagsString.split(" ");
  68510. tags.forEach(function (tag, index, array) {
  68511. Tags._AddTagTo(obj, tag);
  68512. });
  68513. };
  68514. Tags._AddTagTo = function (obj, tag) {
  68515. tag = tag.trim();
  68516. if (tag === "" || tag === "true" || tag === "false") {
  68517. return;
  68518. }
  68519. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  68520. return;
  68521. }
  68522. Tags.EnableFor(obj);
  68523. obj._tags[tag] = true;
  68524. };
  68525. Tags.RemoveTagsFrom = function (obj, tagsString) {
  68526. if (!Tags.HasTags(obj)) {
  68527. return;
  68528. }
  68529. var tags = tagsString.split(" ");
  68530. for (var t in tags) {
  68531. Tags._RemoveTagFrom(obj, tags[t]);
  68532. }
  68533. };
  68534. Tags._RemoveTagFrom = function (obj, tag) {
  68535. delete obj._tags[tag];
  68536. };
  68537. Tags.MatchesQuery = function (obj, tagsQuery) {
  68538. if (tagsQuery === undefined) {
  68539. return true;
  68540. }
  68541. if (tagsQuery === "") {
  68542. return Tags.HasTags(obj);
  68543. }
  68544. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  68545. };
  68546. return Tags;
  68547. }());
  68548. BABYLON.Tags = Tags;
  68549. })(BABYLON || (BABYLON = {}));
  68550. //# sourceMappingURL=babylon.tags.js.map
  68551. var BABYLON;
  68552. (function (BABYLON) {
  68553. /**
  68554. * Class used to evalaute queries containing `and` and `or` operators
  68555. */
  68556. var AndOrNotEvaluator = /** @class */ (function () {
  68557. function AndOrNotEvaluator() {
  68558. }
  68559. /**
  68560. * Evaluate a query
  68561. * @param query defines the query to evaluate
  68562. * @param evaluateCallback defines the callback used to filter result
  68563. * @returns true if the query matches
  68564. */
  68565. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  68566. if (!query.match(/\([^\(\)]*\)/g)) {
  68567. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  68568. }
  68569. else {
  68570. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  68571. // remove parenthesis
  68572. r = r.slice(1, r.length - 1);
  68573. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  68574. });
  68575. }
  68576. if (query === "true") {
  68577. return true;
  68578. }
  68579. if (query === "false") {
  68580. return false;
  68581. }
  68582. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  68583. };
  68584. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  68585. evaluateCallback = evaluateCallback || (function (r) {
  68586. return r === "true" ? true : false;
  68587. });
  68588. var result;
  68589. var or = parenthesisContent.split("||");
  68590. for (var i in or) {
  68591. if (or.hasOwnProperty(i)) {
  68592. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  68593. var and = ori.split("&&");
  68594. if (and.length > 1) {
  68595. for (var j = 0; j < and.length; ++j) {
  68596. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  68597. if (andj !== "true" && andj !== "false") {
  68598. if (andj[0] === "!") {
  68599. result = !evaluateCallback(andj.substring(1));
  68600. }
  68601. else {
  68602. result = evaluateCallback(andj);
  68603. }
  68604. }
  68605. else {
  68606. result = andj === "true" ? true : false;
  68607. }
  68608. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  68609. ori = "false";
  68610. break;
  68611. }
  68612. }
  68613. }
  68614. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  68615. result = true;
  68616. break;
  68617. }
  68618. // result equals false (or undefined)
  68619. if (ori !== "true" && ori !== "false") {
  68620. if (ori[0] === "!") {
  68621. result = !evaluateCallback(ori.substring(1));
  68622. }
  68623. else {
  68624. result = evaluateCallback(ori);
  68625. }
  68626. }
  68627. else {
  68628. result = ori === "true" ? true : false;
  68629. }
  68630. }
  68631. }
  68632. // the whole parenthesis scope is replaced by 'true' or 'false'
  68633. return result ? "true" : "false";
  68634. };
  68635. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  68636. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  68637. // remove whitespaces
  68638. r = r.replace(/[\s]/g, function () { return ""; });
  68639. return r.length % 2 ? "!" : "";
  68640. });
  68641. booleanString = booleanString.trim();
  68642. if (booleanString === "!true") {
  68643. booleanString = "false";
  68644. }
  68645. else if (booleanString === "!false") {
  68646. booleanString = "true";
  68647. }
  68648. return booleanString;
  68649. };
  68650. return AndOrNotEvaluator;
  68651. }());
  68652. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  68653. })(BABYLON || (BABYLON = {}));
  68654. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  68655. var BABYLON;
  68656. (function (BABYLON) {
  68657. /**
  68658. * Class used to enable access to IndexedDB
  68659. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  68660. */
  68661. var Database = /** @class */ (function () {
  68662. /**
  68663. * Creates a new Database
  68664. * @param urlToScene defines the url to load the scene
  68665. * @param callbackManifestChecked defines the callback to use when manifest is checked
  68666. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  68667. */
  68668. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  68669. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  68670. var _this = this;
  68671. // Handling various flavors of prefixed version of IndexedDB
  68672. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  68673. this.callbackManifestChecked = callbackManifestChecked;
  68674. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  68675. this.db = null;
  68676. this._enableSceneOffline = false;
  68677. this._enableTexturesOffline = false;
  68678. this.manifestVersionFound = 0;
  68679. this.mustUpdateRessources = false;
  68680. this.hasReachedQuota = false;
  68681. if (!Database.IDBStorageEnabled) {
  68682. this.callbackManifestChecked(true);
  68683. }
  68684. else {
  68685. if (disableManifestCheck) {
  68686. this._enableSceneOffline = true;
  68687. this._enableTexturesOffline = true;
  68688. this.manifestVersionFound = 1;
  68689. BABYLON.Tools.SetImmediate(function () {
  68690. _this.callbackManifestChecked(true);
  68691. });
  68692. }
  68693. else {
  68694. this._checkManifestFile();
  68695. }
  68696. }
  68697. }
  68698. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  68699. /**
  68700. * Gets a boolean indicating if scene must be saved in the database
  68701. */
  68702. get: function () {
  68703. return this._enableSceneOffline;
  68704. },
  68705. enumerable: true,
  68706. configurable: true
  68707. });
  68708. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  68709. /**
  68710. * Gets a boolean indicating if textures must be saved in the database
  68711. */
  68712. get: function () {
  68713. return this._enableTexturesOffline;
  68714. },
  68715. enumerable: true,
  68716. configurable: true
  68717. });
  68718. Database.prototype._checkManifestFile = function () {
  68719. var _this = this;
  68720. var noManifestFile = function () {
  68721. _this._enableSceneOffline = false;
  68722. _this._enableTexturesOffline = false;
  68723. _this.callbackManifestChecked(false);
  68724. };
  68725. var timeStampUsed = false;
  68726. var manifestURL = this.currentSceneUrl + ".manifest";
  68727. var xhr = new XMLHttpRequest();
  68728. if (navigator.onLine) {
  68729. // Adding a timestamp to by-pass browsers' cache
  68730. timeStampUsed = true;
  68731. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  68732. }
  68733. xhr.open("GET", manifestURL, true);
  68734. xhr.addEventListener("load", function () {
  68735. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  68736. try {
  68737. var manifestFile = JSON.parse(xhr.response);
  68738. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  68739. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  68740. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  68741. _this.manifestVersionFound = manifestFile.version;
  68742. }
  68743. if (_this.callbackManifestChecked) {
  68744. _this.callbackManifestChecked(true);
  68745. }
  68746. }
  68747. catch (ex) {
  68748. noManifestFile();
  68749. }
  68750. }
  68751. else {
  68752. noManifestFile();
  68753. }
  68754. }, false);
  68755. xhr.addEventListener("error", function (event) {
  68756. if (timeStampUsed) {
  68757. timeStampUsed = false;
  68758. // Let's retry without the timeStamp
  68759. // It could fail when coupled with HTML5 Offline API
  68760. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  68761. xhr.open("GET", retryManifestURL, true);
  68762. xhr.send();
  68763. }
  68764. else {
  68765. noManifestFile();
  68766. }
  68767. }, false);
  68768. try {
  68769. xhr.send();
  68770. }
  68771. catch (ex) {
  68772. BABYLON.Tools.Error("Error on XHR send request.");
  68773. this.callbackManifestChecked(false);
  68774. }
  68775. };
  68776. /**
  68777. * Open the database and make it available
  68778. * @param successCallback defines the callback to call on success
  68779. * @param errorCallback defines the callback to call on error
  68780. */
  68781. Database.prototype.openAsync = function (successCallback, errorCallback) {
  68782. var _this = this;
  68783. var handleError = function () {
  68784. _this.isSupported = false;
  68785. if (errorCallback)
  68786. errorCallback();
  68787. };
  68788. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  68789. // Your browser doesn't support IndexedDB
  68790. this.isSupported = false;
  68791. if (errorCallback)
  68792. errorCallback();
  68793. }
  68794. else {
  68795. // If the DB hasn't been opened or created yet
  68796. if (!this.db) {
  68797. this.hasReachedQuota = false;
  68798. this.isSupported = true;
  68799. var request = this.idbFactory.open("babylonjs", 1);
  68800. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  68801. request.onerror = function (event) {
  68802. handleError();
  68803. };
  68804. // executes when a version change transaction cannot complete due to other active transactions
  68805. request.onblocked = function (event) {
  68806. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  68807. handleError();
  68808. };
  68809. // DB has been opened successfully
  68810. request.onsuccess = function (event) {
  68811. _this.db = request.result;
  68812. successCallback();
  68813. };
  68814. // Initialization of the DB. Creating Scenes & Textures stores
  68815. request.onupgradeneeded = function (event) {
  68816. _this.db = (event.target).result;
  68817. if (_this.db) {
  68818. try {
  68819. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  68820. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  68821. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  68822. }
  68823. catch (ex) {
  68824. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  68825. handleError();
  68826. }
  68827. }
  68828. };
  68829. }
  68830. // DB has already been created and opened
  68831. else {
  68832. if (successCallback)
  68833. successCallback();
  68834. }
  68835. }
  68836. };
  68837. /**
  68838. * Loads an image from the database
  68839. * @param url defines the url to load from
  68840. * @param image defines the target DOM image
  68841. */
  68842. Database.prototype.loadImageFromDB = function (url, image) {
  68843. var _this = this;
  68844. var completeURL = Database._ReturnFullUrlLocation(url);
  68845. var saveAndLoadImage = function () {
  68846. if (!_this.hasReachedQuota && _this.db !== null) {
  68847. // the texture is not yet in the DB, let's try to save it
  68848. _this._saveImageIntoDBAsync(completeURL, image);
  68849. }
  68850. // If the texture is not in the DB and we've reached the DB quota limit
  68851. // let's load it directly from the web
  68852. else {
  68853. image.src = url;
  68854. }
  68855. };
  68856. if (!this.mustUpdateRessources) {
  68857. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  68858. }
  68859. // First time we're download the images or update requested in the manifest file by a version change
  68860. else {
  68861. saveAndLoadImage();
  68862. }
  68863. };
  68864. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  68865. if (this.isSupported && this.db !== null) {
  68866. var texture;
  68867. var transaction = this.db.transaction(["textures"]);
  68868. transaction.onabort = function (event) {
  68869. image.src = url;
  68870. };
  68871. transaction.oncomplete = function (event) {
  68872. var blobTextureURL;
  68873. if (texture) {
  68874. var URL = window.URL || window.webkitURL;
  68875. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  68876. image.onerror = function () {
  68877. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  68878. image.src = url;
  68879. };
  68880. image.src = blobTextureURL;
  68881. }
  68882. else {
  68883. notInDBCallback();
  68884. }
  68885. };
  68886. var getRequest = transaction.objectStore("textures").get(url);
  68887. getRequest.onsuccess = function (event) {
  68888. texture = (event.target).result;
  68889. };
  68890. getRequest.onerror = function (event) {
  68891. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  68892. image.src = url;
  68893. };
  68894. }
  68895. else {
  68896. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68897. image.src = url;
  68898. }
  68899. };
  68900. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  68901. var _this = this;
  68902. if (this.isSupported) {
  68903. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  68904. var generateBlobUrl = function () {
  68905. var blobTextureURL;
  68906. if (blob) {
  68907. var URL = window.URL || window.webkitURL;
  68908. try {
  68909. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  68910. }
  68911. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  68912. catch (ex) {
  68913. blobTextureURL = URL.createObjectURL(blob);
  68914. }
  68915. }
  68916. if (blobTextureURL) {
  68917. image.src = blobTextureURL;
  68918. }
  68919. };
  68920. if (Database.IsUASupportingBlobStorage) { // Create XHR
  68921. var xhr = new XMLHttpRequest(), blob;
  68922. xhr.open("GET", url, true);
  68923. xhr.responseType = "blob";
  68924. xhr.addEventListener("load", function () {
  68925. if (xhr.status === 200 && _this.db) {
  68926. // Blob as response (XHR2)
  68927. blob = xhr.response;
  68928. var transaction = _this.db.transaction(["textures"], "readwrite");
  68929. // the transaction could abort because of a QuotaExceededError error
  68930. transaction.onabort = function (event) {
  68931. try {
  68932. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  68933. var srcElement = (event.srcElement || event.target);
  68934. var error = srcElement.error;
  68935. if (error && error.name === "QuotaExceededError") {
  68936. _this.hasReachedQuota = true;
  68937. }
  68938. }
  68939. catch (ex) { }
  68940. generateBlobUrl();
  68941. };
  68942. transaction.oncomplete = function (event) {
  68943. generateBlobUrl();
  68944. };
  68945. var newTexture = { textureUrl: url, data: blob };
  68946. try {
  68947. // Put the blob into the dabase
  68948. var addRequest = transaction.objectStore("textures").put(newTexture);
  68949. addRequest.onsuccess = function (event) {
  68950. };
  68951. addRequest.onerror = function (event) {
  68952. generateBlobUrl();
  68953. };
  68954. }
  68955. catch (ex) {
  68956. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  68957. if (ex.code === 25) {
  68958. Database.IsUASupportingBlobStorage = false;
  68959. }
  68960. image.src = url;
  68961. }
  68962. }
  68963. else {
  68964. image.src = url;
  68965. }
  68966. }, false);
  68967. xhr.addEventListener("error", function (event) {
  68968. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  68969. image.src = url;
  68970. }, false);
  68971. xhr.send();
  68972. }
  68973. else {
  68974. image.src = url;
  68975. }
  68976. }
  68977. else {
  68978. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  68979. image.src = url;
  68980. }
  68981. };
  68982. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  68983. var _this = this;
  68984. var updateVersion = function () {
  68985. // the version is not yet in the DB or we need to update it
  68986. _this._saveVersionIntoDBAsync(url, versionLoaded);
  68987. };
  68988. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  68989. };
  68990. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  68991. var _this = this;
  68992. if (this.isSupported && this.db) {
  68993. var version;
  68994. try {
  68995. var transaction = this.db.transaction(["versions"]);
  68996. transaction.oncomplete = function (event) {
  68997. if (version) {
  68998. // If the version in the JSON file is different from the version in DB
  68999. if (_this.manifestVersionFound !== version.data) {
  69000. _this.mustUpdateRessources = true;
  69001. updateInDBCallback();
  69002. }
  69003. else {
  69004. callback(version.data);
  69005. }
  69006. }
  69007. // version was not found in DB
  69008. else {
  69009. _this.mustUpdateRessources = true;
  69010. updateInDBCallback();
  69011. }
  69012. };
  69013. transaction.onabort = function (event) {
  69014. callback(-1);
  69015. };
  69016. var getRequest = transaction.objectStore("versions").get(url);
  69017. getRequest.onsuccess = function (event) {
  69018. version = (event.target).result;
  69019. };
  69020. getRequest.onerror = function (event) {
  69021. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  69022. callback(-1);
  69023. };
  69024. }
  69025. catch (ex) {
  69026. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  69027. callback(-1);
  69028. }
  69029. }
  69030. else {
  69031. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69032. callback(-1);
  69033. }
  69034. };
  69035. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  69036. var _this = this;
  69037. if (this.isSupported && !this.hasReachedQuota && this.db) {
  69038. try {
  69039. // Open a transaction to the database
  69040. var transaction = this.db.transaction(["versions"], "readwrite");
  69041. // the transaction could abort because of a QuotaExceededError error
  69042. transaction.onabort = function (event) {
  69043. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69044. var error = event.srcElement['error'];
  69045. if (error && error.name === "QuotaExceededError") {
  69046. _this.hasReachedQuota = true;
  69047. }
  69048. }
  69049. catch (ex) { }
  69050. callback(-1);
  69051. };
  69052. transaction.oncomplete = function (event) {
  69053. callback(_this.manifestVersionFound);
  69054. };
  69055. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  69056. // Put the scene into the database
  69057. var addRequest = transaction.objectStore("versions").put(newVersion);
  69058. addRequest.onsuccess = function (event) {
  69059. };
  69060. addRequest.onerror = function (event) {
  69061. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  69062. };
  69063. }
  69064. catch (ex) {
  69065. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  69066. callback(-1);
  69067. }
  69068. }
  69069. else {
  69070. callback(-1);
  69071. }
  69072. };
  69073. /**
  69074. * Loads a file from database
  69075. * @param url defines the URL to load from
  69076. * @param sceneLoaded defines a callback to call on success
  69077. * @param progressCallBack defines a callback to call when progress changed
  69078. * @param errorCallback defines a callback to call on error
  69079. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  69080. */
  69081. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  69082. var _this = this;
  69083. var completeUrl = Database._ReturnFullUrlLocation(url);
  69084. var saveAndLoadFile = function () {
  69085. // the scene is not yet in the DB, let's try to save it
  69086. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  69087. };
  69088. this._checkVersionFromDB(completeUrl, function (version) {
  69089. if (version !== -1) {
  69090. if (!_this.mustUpdateRessources) {
  69091. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  69092. }
  69093. else {
  69094. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  69095. }
  69096. }
  69097. else {
  69098. if (errorCallback) {
  69099. errorCallback();
  69100. }
  69101. }
  69102. });
  69103. };
  69104. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  69105. if (this.isSupported && this.db) {
  69106. var targetStore;
  69107. if (url.indexOf(".babylon") !== -1) {
  69108. targetStore = "scenes";
  69109. }
  69110. else {
  69111. targetStore = "textures";
  69112. }
  69113. var file;
  69114. var transaction = this.db.transaction([targetStore]);
  69115. transaction.oncomplete = function (event) {
  69116. if (file) {
  69117. callback(file.data);
  69118. }
  69119. // file was not found in DB
  69120. else {
  69121. notInDBCallback();
  69122. }
  69123. };
  69124. transaction.onabort = function (event) {
  69125. notInDBCallback();
  69126. };
  69127. var getRequest = transaction.objectStore(targetStore).get(url);
  69128. getRequest.onsuccess = function (event) {
  69129. file = (event.target).result;
  69130. };
  69131. getRequest.onerror = function (event) {
  69132. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  69133. notInDBCallback();
  69134. };
  69135. }
  69136. else {
  69137. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69138. callback();
  69139. }
  69140. };
  69141. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  69142. var _this = this;
  69143. if (this.isSupported) {
  69144. var targetStore;
  69145. if (url.indexOf(".babylon") !== -1) {
  69146. targetStore = "scenes";
  69147. }
  69148. else {
  69149. targetStore = "textures";
  69150. }
  69151. // Create XHR
  69152. var xhr = new XMLHttpRequest();
  69153. var fileData;
  69154. xhr.open("GET", url, true);
  69155. if (useArrayBuffer) {
  69156. xhr.responseType = "arraybuffer";
  69157. }
  69158. if (progressCallback) {
  69159. xhr.onprogress = progressCallback;
  69160. }
  69161. xhr.addEventListener("load", function () {
  69162. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  69163. // Blob as response (XHR2)
  69164. //fileData = xhr.responseText;
  69165. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  69166. if (!_this.hasReachedQuota && _this.db) {
  69167. // Open a transaction to the database
  69168. var transaction = _this.db.transaction([targetStore], "readwrite");
  69169. // the transaction could abort because of a QuotaExceededError error
  69170. transaction.onabort = function (event) {
  69171. try {
  69172. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69173. var error = event.srcElement['error'];
  69174. if (error && error.name === "QuotaExceededError") {
  69175. _this.hasReachedQuota = true;
  69176. }
  69177. }
  69178. catch (ex) { }
  69179. callback(fileData);
  69180. };
  69181. transaction.oncomplete = function (event) {
  69182. callback(fileData);
  69183. };
  69184. var newFile;
  69185. if (targetStore === "scenes") {
  69186. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  69187. }
  69188. else {
  69189. newFile = { textureUrl: url, data: fileData };
  69190. }
  69191. try {
  69192. // Put the scene into the database
  69193. var addRequest = transaction.objectStore(targetStore).put(newFile);
  69194. addRequest.onsuccess = function (event) {
  69195. };
  69196. addRequest.onerror = function (event) {
  69197. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  69198. };
  69199. }
  69200. catch (ex) {
  69201. callback(fileData);
  69202. }
  69203. }
  69204. else {
  69205. callback(fileData);
  69206. }
  69207. }
  69208. else {
  69209. callback();
  69210. }
  69211. }, false);
  69212. xhr.addEventListener("error", function (event) {
  69213. BABYLON.Tools.Error("error on XHR request.");
  69214. callback();
  69215. }, false);
  69216. xhr.send();
  69217. }
  69218. else {
  69219. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69220. callback();
  69221. }
  69222. };
  69223. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  69224. Database.IsUASupportingBlobStorage = true;
  69225. /** Gets a boolean indicating if Database storate is enabled */
  69226. Database.IDBStorageEnabled = true;
  69227. Database._ParseURL = function (url) {
  69228. var a = document.createElement('a');
  69229. a.href = url;
  69230. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  69231. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  69232. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  69233. return absLocation;
  69234. };
  69235. Database._ReturnFullUrlLocation = function (url) {
  69236. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  69237. return (Database._ParseURL(window.location.href) + url);
  69238. }
  69239. else {
  69240. return url;
  69241. }
  69242. };
  69243. return Database;
  69244. }());
  69245. BABYLON.Database = Database;
  69246. })(BABYLON || (BABYLON = {}));
  69247. //# sourceMappingURL=babylon.database.js.map
  69248. var BABYLON;
  69249. (function (BABYLON) {
  69250. var FresnelParameters = /** @class */ (function () {
  69251. function FresnelParameters() {
  69252. this._isEnabled = true;
  69253. this.leftColor = BABYLON.Color3.White();
  69254. this.rightColor = BABYLON.Color3.Black();
  69255. this.bias = 0;
  69256. this.power = 1;
  69257. }
  69258. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  69259. get: function () {
  69260. return this._isEnabled;
  69261. },
  69262. set: function (value) {
  69263. if (this._isEnabled === value) {
  69264. return;
  69265. }
  69266. this._isEnabled = value;
  69267. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  69268. },
  69269. enumerable: true,
  69270. configurable: true
  69271. });
  69272. FresnelParameters.prototype.clone = function () {
  69273. var newFresnelParameters = new FresnelParameters();
  69274. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  69275. return newFresnelParameters;
  69276. };
  69277. FresnelParameters.prototype.serialize = function () {
  69278. var serializationObject = {};
  69279. serializationObject.isEnabled = this.isEnabled;
  69280. serializationObject.leftColor = this.leftColor.asArray();
  69281. serializationObject.rightColor = this.rightColor.asArray();
  69282. serializationObject.bias = this.bias;
  69283. serializationObject.power = this.power;
  69284. return serializationObject;
  69285. };
  69286. FresnelParameters.Parse = function (parsedFresnelParameters) {
  69287. var fresnelParameters = new FresnelParameters();
  69288. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  69289. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  69290. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  69291. fresnelParameters.bias = parsedFresnelParameters.bias;
  69292. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  69293. return fresnelParameters;
  69294. };
  69295. return FresnelParameters;
  69296. }());
  69297. BABYLON.FresnelParameters = FresnelParameters;
  69298. })(BABYLON || (BABYLON = {}));
  69299. //# sourceMappingURL=babylon.fresnelParameters.js.map
  69300. var BABYLON;
  69301. (function (BABYLON) {
  69302. var MultiMaterial = /** @class */ (function (_super) {
  69303. __extends(MultiMaterial, _super);
  69304. function MultiMaterial(name, scene) {
  69305. var _this = _super.call(this, name, scene, true) || this;
  69306. scene.multiMaterials.push(_this);
  69307. _this.subMaterials = new Array();
  69308. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  69309. return _this;
  69310. }
  69311. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  69312. get: function () {
  69313. return this._subMaterials;
  69314. },
  69315. set: function (value) {
  69316. this._subMaterials = value;
  69317. this._hookArray(value);
  69318. },
  69319. enumerable: true,
  69320. configurable: true
  69321. });
  69322. MultiMaterial.prototype._hookArray = function (array) {
  69323. var _this = this;
  69324. var oldPush = array.push;
  69325. array.push = function () {
  69326. var items = [];
  69327. for (var _i = 0; _i < arguments.length; _i++) {
  69328. items[_i] = arguments[_i];
  69329. }
  69330. var result = oldPush.apply(array, items);
  69331. _this._markAllSubMeshesAsTexturesDirty();
  69332. return result;
  69333. };
  69334. var oldSplice = array.splice;
  69335. array.splice = function (index, deleteCount) {
  69336. var deleted = oldSplice.apply(array, [index, deleteCount]);
  69337. _this._markAllSubMeshesAsTexturesDirty();
  69338. return deleted;
  69339. };
  69340. };
  69341. // Properties
  69342. MultiMaterial.prototype.getSubMaterial = function (index) {
  69343. if (index < 0 || index >= this.subMaterials.length) {
  69344. return this.getScene().defaultMaterial;
  69345. }
  69346. return this.subMaterials[index];
  69347. };
  69348. MultiMaterial.prototype.getActiveTextures = function () {
  69349. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  69350. if (subMaterial) {
  69351. return subMaterial.getActiveTextures();
  69352. }
  69353. else {
  69354. return [];
  69355. }
  69356. }));
  69357. var _a;
  69358. };
  69359. // Methods
  69360. MultiMaterial.prototype.getClassName = function () {
  69361. return "MultiMaterial";
  69362. };
  69363. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  69364. for (var index = 0; index < this.subMaterials.length; index++) {
  69365. var subMaterial = this.subMaterials[index];
  69366. if (subMaterial) {
  69367. if (subMaterial.storeEffectOnSubMeshes) {
  69368. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  69369. return false;
  69370. }
  69371. continue;
  69372. }
  69373. if (!subMaterial.isReady(mesh)) {
  69374. return false;
  69375. }
  69376. }
  69377. }
  69378. return true;
  69379. };
  69380. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  69381. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  69382. for (var index = 0; index < this.subMaterials.length; index++) {
  69383. var subMaterial = null;
  69384. var current = this.subMaterials[index];
  69385. if (cloneChildren && current) {
  69386. subMaterial = current.clone(name + "-" + current.name);
  69387. }
  69388. else {
  69389. subMaterial = this.subMaterials[index];
  69390. }
  69391. newMultiMaterial.subMaterials.push(subMaterial);
  69392. }
  69393. return newMultiMaterial;
  69394. };
  69395. MultiMaterial.prototype.serialize = function () {
  69396. var serializationObject = {};
  69397. serializationObject.name = this.name;
  69398. serializationObject.id = this.id;
  69399. if (BABYLON.Tags) {
  69400. serializationObject.tags = BABYLON.Tags.GetTags(this);
  69401. }
  69402. serializationObject.materials = [];
  69403. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  69404. var subMat = this.subMaterials[matIndex];
  69405. if (subMat) {
  69406. serializationObject.materials.push(subMat.id);
  69407. }
  69408. else {
  69409. serializationObject.materials.push(null);
  69410. }
  69411. }
  69412. return serializationObject;
  69413. };
  69414. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  69415. var scene = this.getScene();
  69416. if (!scene) {
  69417. return;
  69418. }
  69419. var index = scene.multiMaterials.indexOf(this);
  69420. if (index >= 0) {
  69421. scene.multiMaterials.splice(index, 1);
  69422. }
  69423. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  69424. };
  69425. return MultiMaterial;
  69426. }(BABYLON.Material));
  69427. BABYLON.MultiMaterial = MultiMaterial;
  69428. })(BABYLON || (BABYLON = {}));
  69429. //# sourceMappingURL=babylon.multiMaterial.js.map
  69430. var BABYLON;
  69431. (function (BABYLON) {
  69432. var FreeCameraTouchInput = /** @class */ (function () {
  69433. function FreeCameraTouchInput() {
  69434. this._offsetX = null;
  69435. this._offsetY = null;
  69436. this._pointerPressed = new Array();
  69437. this.touchAngularSensibility = 200000.0;
  69438. this.touchMoveSensibility = 250.0;
  69439. }
  69440. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  69441. var _this = this;
  69442. var previousPosition = null;
  69443. if (this._pointerInput === undefined) {
  69444. this._onLostFocus = function (evt) {
  69445. _this._offsetX = null;
  69446. _this._offsetY = null;
  69447. };
  69448. this._pointerInput = function (p, s) {
  69449. var evt = p.event;
  69450. if (evt.pointerType === "mouse") {
  69451. return;
  69452. }
  69453. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  69454. if (!noPreventDefault) {
  69455. evt.preventDefault();
  69456. }
  69457. _this._pointerPressed.push(evt.pointerId);
  69458. if (_this._pointerPressed.length !== 1) {
  69459. return;
  69460. }
  69461. previousPosition = {
  69462. x: evt.clientX,
  69463. y: evt.clientY
  69464. };
  69465. }
  69466. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  69467. if (!noPreventDefault) {
  69468. evt.preventDefault();
  69469. }
  69470. var index = _this._pointerPressed.indexOf(evt.pointerId);
  69471. if (index === -1) {
  69472. return;
  69473. }
  69474. _this._pointerPressed.splice(index, 1);
  69475. if (index != 0) {
  69476. return;
  69477. }
  69478. previousPosition = null;
  69479. _this._offsetX = null;
  69480. _this._offsetY = null;
  69481. }
  69482. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  69483. if (!noPreventDefault) {
  69484. evt.preventDefault();
  69485. }
  69486. if (!previousPosition) {
  69487. return;
  69488. }
  69489. var index = _this._pointerPressed.indexOf(evt.pointerId);
  69490. if (index != 0) {
  69491. return;
  69492. }
  69493. _this._offsetX = evt.clientX - previousPosition.x;
  69494. _this._offsetY = -(evt.clientY - previousPosition.y);
  69495. }
  69496. };
  69497. }
  69498. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  69499. if (this._onLostFocus) {
  69500. element.addEventListener("blur", this._onLostFocus);
  69501. }
  69502. };
  69503. FreeCameraTouchInput.prototype.detachControl = function (element) {
  69504. if (this._pointerInput && element) {
  69505. if (this._observer) {
  69506. this.camera.getScene().onPointerObservable.remove(this._observer);
  69507. this._observer = null;
  69508. }
  69509. if (this._onLostFocus) {
  69510. element.removeEventListener("blur", this._onLostFocus);
  69511. this._onLostFocus = null;
  69512. }
  69513. this._pointerPressed = [];
  69514. this._offsetX = null;
  69515. this._offsetY = null;
  69516. }
  69517. };
  69518. FreeCameraTouchInput.prototype.checkInputs = function () {
  69519. if (this._offsetX && this._offsetY) {
  69520. var camera = this.camera;
  69521. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  69522. if (this._pointerPressed.length > 1) {
  69523. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  69524. }
  69525. else {
  69526. var speed = camera._computeLocalCameraSpeed();
  69527. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  69528. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  69529. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  69530. }
  69531. }
  69532. };
  69533. FreeCameraTouchInput.prototype.getClassName = function () {
  69534. return "FreeCameraTouchInput";
  69535. };
  69536. FreeCameraTouchInput.prototype.getSimpleName = function () {
  69537. return "touch";
  69538. };
  69539. __decorate([
  69540. BABYLON.serialize()
  69541. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  69542. __decorate([
  69543. BABYLON.serialize()
  69544. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  69545. return FreeCameraTouchInput;
  69546. }());
  69547. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  69548. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  69549. })(BABYLON || (BABYLON = {}));
  69550. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  69551. var BABYLON;
  69552. (function (BABYLON) {
  69553. // We're mainly based on the logic defined into the FreeCamera code
  69554. var TouchCamera = /** @class */ (function (_super) {
  69555. __extends(TouchCamera, _super);
  69556. //-- end properties for backward compatibility for inputs
  69557. function TouchCamera(name, position, scene) {
  69558. var _this = _super.call(this, name, position, scene) || this;
  69559. _this.inputs.addTouch();
  69560. _this._setupInputs();
  69561. return _this;
  69562. }
  69563. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  69564. //-- Begin properties for backward compatibility for inputs
  69565. get: function () {
  69566. var touch = this.inputs.attached["touch"];
  69567. if (touch)
  69568. return touch.touchAngularSensibility;
  69569. return 0;
  69570. },
  69571. set: function (value) {
  69572. var touch = this.inputs.attached["touch"];
  69573. if (touch)
  69574. touch.touchAngularSensibility = value;
  69575. },
  69576. enumerable: true,
  69577. configurable: true
  69578. });
  69579. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  69580. get: function () {
  69581. var touch = this.inputs.attached["touch"];
  69582. if (touch)
  69583. return touch.touchMoveSensibility;
  69584. return 0;
  69585. },
  69586. set: function (value) {
  69587. var touch = this.inputs.attached["touch"];
  69588. if (touch)
  69589. touch.touchMoveSensibility = value;
  69590. },
  69591. enumerable: true,
  69592. configurable: true
  69593. });
  69594. TouchCamera.prototype.getClassName = function () {
  69595. return "TouchCamera";
  69596. };
  69597. TouchCamera.prototype._setupInputs = function () {
  69598. var mouse = this.inputs.attached["mouse"];
  69599. if (mouse) {
  69600. mouse.touchEnabled = false;
  69601. }
  69602. };
  69603. return TouchCamera;
  69604. }(BABYLON.FreeCamera));
  69605. BABYLON.TouchCamera = TouchCamera;
  69606. })(BABYLON || (BABYLON = {}));
  69607. //# sourceMappingURL=babylon.touchCamera.js.map
  69608. var BABYLON;
  69609. (function (BABYLON) {
  69610. var ProceduralTexture = /** @class */ (function (_super) {
  69611. __extends(ProceduralTexture, _super);
  69612. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  69613. if (fallbackTexture === void 0) { fallbackTexture = null; }
  69614. if (generateMipMaps === void 0) { generateMipMaps = true; }
  69615. if (isCube === void 0) { isCube = false; }
  69616. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  69617. _this.isCube = isCube;
  69618. _this.isEnabled = true;
  69619. _this._currentRefreshId = -1;
  69620. _this._refreshRate = 1;
  69621. _this._vertexBuffers = {};
  69622. _this._uniforms = new Array();
  69623. _this._samplers = new Array();
  69624. _this._textures = {};
  69625. _this._floats = {};
  69626. _this._floatsArrays = {};
  69627. _this._colors3 = {};
  69628. _this._colors4 = {};
  69629. _this._vectors2 = {};
  69630. _this._vectors3 = {};
  69631. _this._matrices = {};
  69632. _this._fallbackTextureUsed = false;
  69633. scene.proceduralTextures.push(_this);
  69634. _this._engine = scene.getEngine();
  69635. _this.name = name;
  69636. _this.isRenderTarget = true;
  69637. _this._size = size;
  69638. _this._generateMipMaps = generateMipMaps;
  69639. _this.setFragment(fragment);
  69640. _this._fallbackTexture = fallbackTexture;
  69641. if (isCube) {
  69642. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  69643. _this.setFloat("face", 0);
  69644. }
  69645. else {
  69646. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  69647. }
  69648. // VBO
  69649. var vertices = [];
  69650. vertices.push(1, 1);
  69651. vertices.push(-1, 1);
  69652. vertices.push(-1, -1);
  69653. vertices.push(1, -1);
  69654. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  69655. _this._createIndexBuffer();
  69656. return _this;
  69657. }
  69658. ProceduralTexture.prototype._createIndexBuffer = function () {
  69659. var engine = this._engine;
  69660. // Indices
  69661. var indices = [];
  69662. indices.push(0);
  69663. indices.push(1);
  69664. indices.push(2);
  69665. indices.push(0);
  69666. indices.push(2);
  69667. indices.push(3);
  69668. this._indexBuffer = engine.createIndexBuffer(indices);
  69669. };
  69670. ProceduralTexture.prototype._rebuild = function () {
  69671. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69672. if (vb) {
  69673. vb._rebuild();
  69674. }
  69675. this._createIndexBuffer();
  69676. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  69677. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  69678. }
  69679. };
  69680. ProceduralTexture.prototype.reset = function () {
  69681. if (this._effect === undefined) {
  69682. return;
  69683. }
  69684. var engine = this._engine;
  69685. engine._releaseEffect(this._effect);
  69686. };
  69687. ProceduralTexture.prototype.isReady = function () {
  69688. var _this = this;
  69689. var engine = this._engine;
  69690. var shaders;
  69691. if (!this._fragment) {
  69692. return false;
  69693. }
  69694. if (this._fallbackTextureUsed) {
  69695. return true;
  69696. }
  69697. if (this._fragment.fragmentElement !== undefined) {
  69698. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  69699. }
  69700. else {
  69701. shaders = { vertex: "procedural", fragment: this._fragment };
  69702. }
  69703. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  69704. _this.releaseInternalTexture();
  69705. if (_this._fallbackTexture) {
  69706. _this._texture = _this._fallbackTexture._texture;
  69707. if (_this._texture) {
  69708. _this._texture.incrementReferences();
  69709. }
  69710. }
  69711. _this._fallbackTextureUsed = true;
  69712. });
  69713. return this._effect.isReady();
  69714. };
  69715. ProceduralTexture.prototype.resetRefreshCounter = function () {
  69716. this._currentRefreshId = -1;
  69717. };
  69718. ProceduralTexture.prototype.setFragment = function (fragment) {
  69719. this._fragment = fragment;
  69720. };
  69721. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  69722. get: function () {
  69723. return this._refreshRate;
  69724. },
  69725. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  69726. set: function (value) {
  69727. this._refreshRate = value;
  69728. this.resetRefreshCounter();
  69729. },
  69730. enumerable: true,
  69731. configurable: true
  69732. });
  69733. ProceduralTexture.prototype._shouldRender = function () {
  69734. if (!this.isEnabled || !this.isReady() || !this._texture) {
  69735. return false;
  69736. }
  69737. if (this._fallbackTextureUsed) {
  69738. return false;
  69739. }
  69740. if (this._currentRefreshId === -1) { // At least render once
  69741. this._currentRefreshId = 1;
  69742. return true;
  69743. }
  69744. if (this.refreshRate === this._currentRefreshId) {
  69745. this._currentRefreshId = 1;
  69746. return true;
  69747. }
  69748. this._currentRefreshId++;
  69749. return false;
  69750. };
  69751. ProceduralTexture.prototype.getRenderSize = function () {
  69752. return this._size;
  69753. };
  69754. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  69755. if (this._fallbackTextureUsed) {
  69756. return;
  69757. }
  69758. this.releaseInternalTexture();
  69759. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  69760. };
  69761. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  69762. if (this._uniforms.indexOf(uniformName) === -1) {
  69763. this._uniforms.push(uniformName);
  69764. }
  69765. };
  69766. ProceduralTexture.prototype.setTexture = function (name, texture) {
  69767. if (this._samplers.indexOf(name) === -1) {
  69768. this._samplers.push(name);
  69769. }
  69770. this._textures[name] = texture;
  69771. return this;
  69772. };
  69773. ProceduralTexture.prototype.setFloat = function (name, value) {
  69774. this._checkUniform(name);
  69775. this._floats[name] = value;
  69776. return this;
  69777. };
  69778. ProceduralTexture.prototype.setFloats = function (name, value) {
  69779. this._checkUniform(name);
  69780. this._floatsArrays[name] = value;
  69781. return this;
  69782. };
  69783. ProceduralTexture.prototype.setColor3 = function (name, value) {
  69784. this._checkUniform(name);
  69785. this._colors3[name] = value;
  69786. return this;
  69787. };
  69788. ProceduralTexture.prototype.setColor4 = function (name, value) {
  69789. this._checkUniform(name);
  69790. this._colors4[name] = value;
  69791. return this;
  69792. };
  69793. ProceduralTexture.prototype.setVector2 = function (name, value) {
  69794. this._checkUniform(name);
  69795. this._vectors2[name] = value;
  69796. return this;
  69797. };
  69798. ProceduralTexture.prototype.setVector3 = function (name, value) {
  69799. this._checkUniform(name);
  69800. this._vectors3[name] = value;
  69801. return this;
  69802. };
  69803. ProceduralTexture.prototype.setMatrix = function (name, value) {
  69804. this._checkUniform(name);
  69805. this._matrices[name] = value;
  69806. return this;
  69807. };
  69808. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  69809. var scene = this.getScene();
  69810. if (!scene) {
  69811. return;
  69812. }
  69813. var engine = this._engine;
  69814. // Render
  69815. engine.enableEffect(this._effect);
  69816. engine.setState(false);
  69817. // Texture
  69818. for (var name in this._textures) {
  69819. this._effect.setTexture(name, this._textures[name]);
  69820. }
  69821. // Float
  69822. for (name in this._floats) {
  69823. this._effect.setFloat(name, this._floats[name]);
  69824. }
  69825. // Floats
  69826. for (name in this._floatsArrays) {
  69827. this._effect.setArray(name, this._floatsArrays[name]);
  69828. }
  69829. // Color3
  69830. for (name in this._colors3) {
  69831. this._effect.setColor3(name, this._colors3[name]);
  69832. }
  69833. // Color4
  69834. for (name in this._colors4) {
  69835. var color = this._colors4[name];
  69836. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  69837. }
  69838. // Vector2
  69839. for (name in this._vectors2) {
  69840. this._effect.setVector2(name, this._vectors2[name]);
  69841. }
  69842. // Vector3
  69843. for (name in this._vectors3) {
  69844. this._effect.setVector3(name, this._vectors3[name]);
  69845. }
  69846. // Matrix
  69847. for (name in this._matrices) {
  69848. this._effect.setMatrix(name, this._matrices[name]);
  69849. }
  69850. if (!this._texture) {
  69851. return;
  69852. }
  69853. if (this.isCube) {
  69854. for (var face = 0; face < 6; face++) {
  69855. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  69856. // VBOs
  69857. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  69858. this._effect.setFloat("face", face);
  69859. // Clear
  69860. engine.clear(scene.clearColor, true, true, true);
  69861. // Draw order
  69862. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  69863. // Mipmaps
  69864. if (face === 5) {
  69865. engine.generateMipMapsForCubemap(this._texture);
  69866. }
  69867. }
  69868. }
  69869. else {
  69870. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  69871. // VBOs
  69872. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  69873. // Clear
  69874. engine.clear(scene.clearColor, true, true, true);
  69875. // Draw order
  69876. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  69877. }
  69878. // Unbind
  69879. engine.unBindFramebuffer(this._texture, this.isCube);
  69880. if (this.onGenerated) {
  69881. this.onGenerated();
  69882. }
  69883. };
  69884. ProceduralTexture.prototype.clone = function () {
  69885. var textureSize = this.getSize();
  69886. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  69887. // Base texture
  69888. newTexture.hasAlpha = this.hasAlpha;
  69889. newTexture.level = this.level;
  69890. // RenderTarget Texture
  69891. newTexture.coordinatesMode = this.coordinatesMode;
  69892. return newTexture;
  69893. };
  69894. ProceduralTexture.prototype.dispose = function () {
  69895. var scene = this.getScene();
  69896. if (!scene) {
  69897. return;
  69898. }
  69899. var index = scene.proceduralTextures.indexOf(this);
  69900. if (index >= 0) {
  69901. scene.proceduralTextures.splice(index, 1);
  69902. }
  69903. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69904. if (vertexBuffer) {
  69905. vertexBuffer.dispose();
  69906. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  69907. }
  69908. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  69909. this._indexBuffer = null;
  69910. }
  69911. _super.prototype.dispose.call(this);
  69912. };
  69913. return ProceduralTexture;
  69914. }(BABYLON.Texture));
  69915. BABYLON.ProceduralTexture = ProceduralTexture;
  69916. })(BABYLON || (BABYLON = {}));
  69917. //# sourceMappingURL=babylon.proceduralTexture.js.map
  69918. var BABYLON;
  69919. (function (BABYLON) {
  69920. var CustomProceduralTexture = /** @class */ (function (_super) {
  69921. __extends(CustomProceduralTexture, _super);
  69922. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  69923. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  69924. _this._animate = true;
  69925. _this._time = 0;
  69926. _this._texturePath = texturePath;
  69927. //Try to load json
  69928. _this.loadJson(texturePath);
  69929. _this.refreshRate = 1;
  69930. return _this;
  69931. }
  69932. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  69933. var _this = this;
  69934. var noConfigFile = function () {
  69935. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  69936. try {
  69937. _this.setFragment(_this._texturePath);
  69938. }
  69939. catch (ex) {
  69940. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  69941. }
  69942. };
  69943. var configFileUrl = jsonUrl + "/config.json";
  69944. var xhr = new XMLHttpRequest();
  69945. xhr.open("GET", configFileUrl, true);
  69946. xhr.addEventListener("load", function () {
  69947. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  69948. try {
  69949. _this._config = JSON.parse(xhr.response);
  69950. _this.updateShaderUniforms();
  69951. _this.updateTextures();
  69952. _this.setFragment(_this._texturePath + "/custom");
  69953. _this._animate = _this._config.animate;
  69954. _this.refreshRate = _this._config.refreshrate;
  69955. }
  69956. catch (ex) {
  69957. noConfigFile();
  69958. }
  69959. }
  69960. else {
  69961. noConfigFile();
  69962. }
  69963. }, false);
  69964. xhr.addEventListener("error", function () {
  69965. noConfigFile();
  69966. }, false);
  69967. try {
  69968. xhr.send();
  69969. }
  69970. catch (ex) {
  69971. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  69972. }
  69973. };
  69974. CustomProceduralTexture.prototype.isReady = function () {
  69975. if (!_super.prototype.isReady.call(this)) {
  69976. return false;
  69977. }
  69978. for (var name in this._textures) {
  69979. var texture = this._textures[name];
  69980. if (!texture.isReady()) {
  69981. return false;
  69982. }
  69983. }
  69984. return true;
  69985. };
  69986. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  69987. var scene = this.getScene();
  69988. if (this._animate && scene) {
  69989. this._time += scene.getAnimationRatio() * 0.03;
  69990. this.updateShaderUniforms();
  69991. }
  69992. _super.prototype.render.call(this, useCameraPostProcess);
  69993. };
  69994. CustomProceduralTexture.prototype.updateTextures = function () {
  69995. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  69996. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  69997. }
  69998. };
  69999. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  70000. if (this._config) {
  70001. for (var j = 0; j < this._config.uniforms.length; j++) {
  70002. var uniform = this._config.uniforms[j];
  70003. switch (uniform.type) {
  70004. case "float":
  70005. this.setFloat(uniform.name, uniform.value);
  70006. break;
  70007. case "color3":
  70008. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  70009. break;
  70010. case "color4":
  70011. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  70012. break;
  70013. case "vector2":
  70014. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  70015. break;
  70016. case "vector3":
  70017. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  70018. break;
  70019. }
  70020. }
  70021. }
  70022. this.setFloat("time", this._time);
  70023. };
  70024. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  70025. get: function () {
  70026. return this._animate;
  70027. },
  70028. set: function (value) {
  70029. this._animate = value;
  70030. },
  70031. enumerable: true,
  70032. configurable: true
  70033. });
  70034. return CustomProceduralTexture;
  70035. }(BABYLON.ProceduralTexture));
  70036. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  70037. })(BABYLON || (BABYLON = {}));
  70038. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  70039. var BABYLON;
  70040. (function (BABYLON) {
  70041. var FreeCameraGamepadInput = /** @class */ (function () {
  70042. function FreeCameraGamepadInput() {
  70043. this.gamepadAngularSensibility = 200;
  70044. this.gamepadMoveSensibility = 40;
  70045. // private members
  70046. this._cameraTransform = BABYLON.Matrix.Identity();
  70047. this._deltaTransform = BABYLON.Vector3.Zero();
  70048. this._vector3 = BABYLON.Vector3.Zero();
  70049. this._vector2 = BABYLON.Vector2.Zero();
  70050. }
  70051. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  70052. var _this = this;
  70053. var manager = this.camera.getScene().gamepadManager;
  70054. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70055. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  70056. // prioritize XBOX gamepads.
  70057. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  70058. _this.gamepad = gamepad;
  70059. }
  70060. }
  70061. });
  70062. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70063. if (_this.gamepad === gamepad) {
  70064. _this.gamepad = null;
  70065. }
  70066. });
  70067. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  70068. };
  70069. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  70070. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70071. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70072. this.gamepad = null;
  70073. };
  70074. FreeCameraGamepadInput.prototype.checkInputs = function () {
  70075. if (this.gamepad && this.gamepad.leftStick) {
  70076. var camera = this.camera;
  70077. var LSValues = this.gamepad.leftStick;
  70078. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  70079. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70080. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  70081. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  70082. var RSValues = this.gamepad.rightStick;
  70083. if (RSValues) {
  70084. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  70085. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  70086. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  70087. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  70088. }
  70089. else {
  70090. RSValues = { x: 0, y: 0 };
  70091. }
  70092. if (!camera.rotationQuaternion) {
  70093. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  70094. }
  70095. else {
  70096. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  70097. }
  70098. var speed = camera._computeLocalCameraSpeed() * 50.0;
  70099. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  70100. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  70101. camera.cameraDirection.addInPlace(this._deltaTransform);
  70102. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  70103. camera.cameraRotation.addInPlace(this._vector2);
  70104. }
  70105. };
  70106. FreeCameraGamepadInput.prototype.getClassName = function () {
  70107. return "FreeCameraGamepadInput";
  70108. };
  70109. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  70110. return "gamepad";
  70111. };
  70112. __decorate([
  70113. BABYLON.serialize()
  70114. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  70115. __decorate([
  70116. BABYLON.serialize()
  70117. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70118. return FreeCameraGamepadInput;
  70119. }());
  70120. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  70121. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  70122. })(BABYLON || (BABYLON = {}));
  70123. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  70124. var BABYLON;
  70125. (function (BABYLON) {
  70126. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  70127. function ArcRotateCameraGamepadInput() {
  70128. this.gamepadRotationSensibility = 80;
  70129. this.gamepadMoveSensibility = 40;
  70130. }
  70131. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  70132. var _this = this;
  70133. var manager = this.camera.getScene().gamepadManager;
  70134. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70135. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  70136. // prioritize XBOX gamepads.
  70137. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  70138. _this.gamepad = gamepad;
  70139. }
  70140. }
  70141. });
  70142. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70143. if (_this.gamepad === gamepad) {
  70144. _this.gamepad = null;
  70145. }
  70146. });
  70147. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  70148. };
  70149. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  70150. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70151. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70152. this.gamepad = null;
  70153. };
  70154. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  70155. if (this.gamepad) {
  70156. var camera = this.camera;
  70157. var RSValues = this.gamepad.rightStick;
  70158. if (RSValues) {
  70159. if (RSValues.x != 0) {
  70160. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  70161. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  70162. camera.inertialAlphaOffset += normalizedRX;
  70163. }
  70164. }
  70165. if (RSValues.y != 0) {
  70166. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  70167. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  70168. camera.inertialBetaOffset += normalizedRY;
  70169. }
  70170. }
  70171. }
  70172. var LSValues = this.gamepad.leftStick;
  70173. if (LSValues && LSValues.y != 0) {
  70174. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70175. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  70176. this.camera.inertialRadiusOffset -= normalizedLY;
  70177. }
  70178. }
  70179. }
  70180. };
  70181. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  70182. return "ArcRotateCameraGamepadInput";
  70183. };
  70184. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  70185. return "gamepad";
  70186. };
  70187. __decorate([
  70188. BABYLON.serialize()
  70189. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  70190. __decorate([
  70191. BABYLON.serialize()
  70192. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70193. return ArcRotateCameraGamepadInput;
  70194. }());
  70195. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  70196. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  70197. })(BABYLON || (BABYLON = {}));
  70198. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  70199. var BABYLON;
  70200. (function (BABYLON) {
  70201. var GamepadManager = /** @class */ (function () {
  70202. function GamepadManager(_scene) {
  70203. var _this = this;
  70204. this._scene = _scene;
  70205. this._babylonGamepads = [];
  70206. this._oneGamepadConnected = false;
  70207. this._isMonitoring = false;
  70208. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  70209. if (!BABYLON.Tools.IsWindowObjectExist()) {
  70210. this._gamepadEventSupported = false;
  70211. }
  70212. else {
  70213. this._gamepadEventSupported = 'GamepadEvent' in window;
  70214. this._gamepadSupport = (navigator.getGamepads ||
  70215. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  70216. }
  70217. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  70218. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  70219. for (var i in _this._babylonGamepads) {
  70220. var gamepad = _this._babylonGamepads[i];
  70221. if (gamepad && gamepad._isConnected) {
  70222. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  70223. }
  70224. }
  70225. });
  70226. this._onGamepadConnectedEvent = function (evt) {
  70227. var gamepad = evt.gamepad;
  70228. if (gamepad.index in _this._babylonGamepads) {
  70229. if (_this._babylonGamepads[gamepad.index].isConnected) {
  70230. return;
  70231. }
  70232. }
  70233. var newGamepad;
  70234. if (_this._babylonGamepads[gamepad.index]) {
  70235. newGamepad = _this._babylonGamepads[gamepad.index];
  70236. newGamepad.browserGamepad = gamepad;
  70237. newGamepad._isConnected = true;
  70238. }
  70239. else {
  70240. newGamepad = _this._addNewGamepad(gamepad);
  70241. }
  70242. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  70243. _this._startMonitoringGamepads();
  70244. };
  70245. this._onGamepadDisconnectedEvent = function (evt) {
  70246. var gamepad = evt.gamepad;
  70247. // Remove the gamepad from the list of gamepads to monitor.
  70248. for (var i in _this._babylonGamepads) {
  70249. if (_this._babylonGamepads[i].index === gamepad.index) {
  70250. var disconnectedGamepad = _this._babylonGamepads[i];
  70251. disconnectedGamepad._isConnected = false;
  70252. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  70253. break;
  70254. }
  70255. }
  70256. };
  70257. if (this._gamepadSupport) {
  70258. //first add already-connected gamepads
  70259. this._updateGamepadObjects();
  70260. if (this._babylonGamepads.length) {
  70261. this._startMonitoringGamepads();
  70262. }
  70263. // Checking if the gamepad connected event is supported (like in Firefox)
  70264. if (this._gamepadEventSupported) {
  70265. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  70266. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  70267. }
  70268. else {
  70269. this._startMonitoringGamepads();
  70270. }
  70271. }
  70272. }
  70273. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  70274. get: function () {
  70275. return this._babylonGamepads;
  70276. },
  70277. enumerable: true,
  70278. configurable: true
  70279. });
  70280. GamepadManager.prototype.getGamepadByType = function (type) {
  70281. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  70282. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  70283. var gamepad = _a[_i];
  70284. if (gamepad && gamepad.type === type) {
  70285. return gamepad;
  70286. }
  70287. }
  70288. return null;
  70289. };
  70290. GamepadManager.prototype.dispose = function () {
  70291. if (this._gamepadEventSupported) {
  70292. if (this._onGamepadConnectedEvent) {
  70293. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  70294. }
  70295. if (this._onGamepadDisconnectedEvent) {
  70296. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  70297. }
  70298. this._onGamepadConnectedEvent = null;
  70299. this._onGamepadDisconnectedEvent = null;
  70300. }
  70301. this._babylonGamepads.forEach(function (gamepad) {
  70302. gamepad.dispose();
  70303. });
  70304. this.onGamepadConnectedObservable.clear();
  70305. this.onGamepadDisconnectedObservable.clear();
  70306. this._oneGamepadConnected = false;
  70307. this._stopMonitoringGamepads();
  70308. this._babylonGamepads = [];
  70309. };
  70310. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  70311. if (!this._oneGamepadConnected) {
  70312. this._oneGamepadConnected = true;
  70313. }
  70314. var newGamepad;
  70315. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  70316. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  70317. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  70318. }
  70319. // if pose is supported, use the (WebVR) pose enabled controller
  70320. else if (gamepad.pose) {
  70321. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  70322. }
  70323. else {
  70324. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  70325. }
  70326. this._babylonGamepads[newGamepad.index] = newGamepad;
  70327. return newGamepad;
  70328. };
  70329. GamepadManager.prototype._startMonitoringGamepads = function () {
  70330. if (!this._isMonitoring) {
  70331. this._isMonitoring = true;
  70332. //back-comp
  70333. if (!this._scene) {
  70334. this._checkGamepadsStatus();
  70335. }
  70336. }
  70337. };
  70338. GamepadManager.prototype._stopMonitoringGamepads = function () {
  70339. this._isMonitoring = false;
  70340. };
  70341. GamepadManager.prototype._checkGamepadsStatus = function () {
  70342. var _this = this;
  70343. // Hack to be compatible Chrome
  70344. this._updateGamepadObjects();
  70345. for (var i in this._babylonGamepads) {
  70346. var gamepad = this._babylonGamepads[i];
  70347. if (!gamepad || !gamepad.isConnected) {
  70348. continue;
  70349. }
  70350. gamepad.update();
  70351. }
  70352. if (this._isMonitoring && !this._scene) {
  70353. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  70354. }
  70355. };
  70356. // This function is called only on Chrome, which does not properly support
  70357. // connection/disconnection events and forces you to recopy again the gamepad object
  70358. GamepadManager.prototype._updateGamepadObjects = function () {
  70359. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  70360. for (var i = 0; i < gamepads.length; i++) {
  70361. var gamepad = gamepads[i];
  70362. if (gamepad) {
  70363. if (!this._babylonGamepads[gamepad.index]) {
  70364. var newGamepad = this._addNewGamepad(gamepad);
  70365. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  70366. }
  70367. else {
  70368. // Forced to copy again this object for Chrome for unknown reason
  70369. this._babylonGamepads[i].browserGamepad = gamepad;
  70370. if (!this._babylonGamepads[i].isConnected) {
  70371. this._babylonGamepads[i]._isConnected = true;
  70372. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  70373. }
  70374. }
  70375. }
  70376. }
  70377. };
  70378. return GamepadManager;
  70379. }());
  70380. BABYLON.GamepadManager = GamepadManager;
  70381. })(BABYLON || (BABYLON = {}));
  70382. //# sourceMappingURL=babylon.gamepadManager.js.map
  70383. var BABYLON;
  70384. (function (BABYLON) {
  70385. var StickValues = /** @class */ (function () {
  70386. function StickValues(x, y) {
  70387. this.x = x;
  70388. this.y = y;
  70389. }
  70390. return StickValues;
  70391. }());
  70392. BABYLON.StickValues = StickValues;
  70393. var Gamepad = /** @class */ (function () {
  70394. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  70395. if (leftStickX === void 0) { leftStickX = 0; }
  70396. if (leftStickY === void 0) { leftStickY = 1; }
  70397. if (rightStickX === void 0) { rightStickX = 2; }
  70398. if (rightStickY === void 0) { rightStickY = 3; }
  70399. this.id = id;
  70400. this.index = index;
  70401. this.browserGamepad = browserGamepad;
  70402. this._isConnected = true;
  70403. this._invertLeftStickY = false;
  70404. this.type = Gamepad.GAMEPAD;
  70405. this._leftStickAxisX = leftStickX;
  70406. this._leftStickAxisY = leftStickY;
  70407. this._rightStickAxisX = rightStickX;
  70408. this._rightStickAxisY = rightStickY;
  70409. if (this.browserGamepad.axes.length >= 2) {
  70410. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  70411. }
  70412. if (this.browserGamepad.axes.length >= 4) {
  70413. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  70414. }
  70415. }
  70416. Object.defineProperty(Gamepad.prototype, "isConnected", {
  70417. get: function () {
  70418. return this._isConnected;
  70419. },
  70420. enumerable: true,
  70421. configurable: true
  70422. });
  70423. Gamepad.prototype.onleftstickchanged = function (callback) {
  70424. this._onleftstickchanged = callback;
  70425. };
  70426. Gamepad.prototype.onrightstickchanged = function (callback) {
  70427. this._onrightstickchanged = callback;
  70428. };
  70429. Object.defineProperty(Gamepad.prototype, "leftStick", {
  70430. get: function () {
  70431. return this._leftStick;
  70432. },
  70433. set: function (newValues) {
  70434. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  70435. this._onleftstickchanged(newValues);
  70436. }
  70437. this._leftStick = newValues;
  70438. },
  70439. enumerable: true,
  70440. configurable: true
  70441. });
  70442. Object.defineProperty(Gamepad.prototype, "rightStick", {
  70443. get: function () {
  70444. return this._rightStick;
  70445. },
  70446. set: function (newValues) {
  70447. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  70448. this._onrightstickchanged(newValues);
  70449. }
  70450. this._rightStick = newValues;
  70451. },
  70452. enumerable: true,
  70453. configurable: true
  70454. });
  70455. Gamepad.prototype.update = function () {
  70456. if (this._leftStick) {
  70457. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  70458. if (this._invertLeftStickY) {
  70459. this.leftStick.y *= -1;
  70460. }
  70461. }
  70462. if (this._rightStick) {
  70463. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  70464. }
  70465. };
  70466. Gamepad.prototype.dispose = function () {
  70467. };
  70468. Gamepad.GAMEPAD = 0;
  70469. Gamepad.GENERIC = 1;
  70470. Gamepad.XBOX = 2;
  70471. Gamepad.POSE_ENABLED = 3;
  70472. return Gamepad;
  70473. }());
  70474. BABYLON.Gamepad = Gamepad;
  70475. var GenericPad = /** @class */ (function (_super) {
  70476. __extends(GenericPad, _super);
  70477. function GenericPad(id, index, browserGamepad) {
  70478. var _this = _super.call(this, id, index, browserGamepad) || this;
  70479. _this.onButtonDownObservable = new BABYLON.Observable();
  70480. _this.onButtonUpObservable = new BABYLON.Observable();
  70481. _this.type = Gamepad.GENERIC;
  70482. _this._buttons = new Array(browserGamepad.buttons.length);
  70483. return _this;
  70484. }
  70485. GenericPad.prototype.onbuttondown = function (callback) {
  70486. this._onbuttondown = callback;
  70487. };
  70488. GenericPad.prototype.onbuttonup = function (callback) {
  70489. this._onbuttonup = callback;
  70490. };
  70491. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  70492. if (newValue !== currentValue) {
  70493. if (newValue === 1) {
  70494. if (this._onbuttondown) {
  70495. this._onbuttondown(buttonIndex);
  70496. }
  70497. this.onButtonDownObservable.notifyObservers(buttonIndex);
  70498. }
  70499. if (newValue === 0) {
  70500. if (this._onbuttonup) {
  70501. this._onbuttonup(buttonIndex);
  70502. }
  70503. this.onButtonUpObservable.notifyObservers(buttonIndex);
  70504. }
  70505. }
  70506. return newValue;
  70507. };
  70508. GenericPad.prototype.update = function () {
  70509. _super.prototype.update.call(this);
  70510. for (var index = 0; index < this._buttons.length; index++) {
  70511. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  70512. }
  70513. };
  70514. GenericPad.prototype.dispose = function () {
  70515. _super.prototype.dispose.call(this);
  70516. this.onButtonDownObservable.clear();
  70517. this.onButtonUpObservable.clear();
  70518. };
  70519. return GenericPad;
  70520. }(Gamepad));
  70521. BABYLON.GenericPad = GenericPad;
  70522. })(BABYLON || (BABYLON = {}));
  70523. //# sourceMappingURL=babylon.gamepad.js.map
  70524. var BABYLON;
  70525. (function (BABYLON) {
  70526. /**
  70527. * Defines supported buttons for XBox360 compatible gamepads
  70528. */
  70529. var Xbox360Button;
  70530. (function (Xbox360Button) {
  70531. /** A */
  70532. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  70533. /** B */
  70534. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  70535. /** X */
  70536. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  70537. /** Y */
  70538. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  70539. /** Start */
  70540. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  70541. /** Back */
  70542. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  70543. /** Left button */
  70544. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  70545. /** Right button */
  70546. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  70547. /** Left stick */
  70548. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  70549. /** Right stick */
  70550. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  70551. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  70552. /** Defines values for XBox360 DPad */
  70553. var Xbox360Dpad;
  70554. (function (Xbox360Dpad) {
  70555. /** Up */
  70556. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  70557. /** Down */
  70558. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  70559. /** Left */
  70560. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  70561. /** Right */
  70562. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  70563. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  70564. /**
  70565. * Defines a XBox360 gamepad
  70566. */
  70567. var Xbox360Pad = /** @class */ (function (_super) {
  70568. __extends(Xbox360Pad, _super);
  70569. /**
  70570. * Creates a new XBox360 gamepad object
  70571. * @param id defines the id of this gamepad
  70572. * @param index defines its index
  70573. * @param gamepad defines the internal HTML gamepad object
  70574. * @param xboxOne defines if it is a XBox One gamepad
  70575. */
  70576. function Xbox360Pad(id, index, gamepad, xboxOne) {
  70577. if (xboxOne === void 0) { xboxOne = false; }
  70578. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  70579. _this._leftTrigger = 0;
  70580. _this._rightTrigger = 0;
  70581. /** Observable raised when a button is pressed */
  70582. _this.onButtonDownObservable = new BABYLON.Observable();
  70583. /** Observable raised when a button is released */
  70584. _this.onButtonUpObservable = new BABYLON.Observable();
  70585. /** Observable raised when a pad is pressed */
  70586. _this.onPadDownObservable = new BABYLON.Observable();
  70587. /** Observable raised when a pad is released */
  70588. _this.onPadUpObservable = new BABYLON.Observable();
  70589. _this._buttonA = 0;
  70590. _this._buttonB = 0;
  70591. _this._buttonX = 0;
  70592. _this._buttonY = 0;
  70593. _this._buttonBack = 0;
  70594. _this._buttonStart = 0;
  70595. _this._buttonLB = 0;
  70596. _this._buttonRB = 0;
  70597. _this._buttonLeftStick = 0;
  70598. _this._buttonRightStick = 0;
  70599. _this._dPadUp = 0;
  70600. _this._dPadDown = 0;
  70601. _this._dPadLeft = 0;
  70602. _this._dPadRight = 0;
  70603. _this._isXboxOnePad = false;
  70604. _this.type = BABYLON.Gamepad.XBOX;
  70605. _this._isXboxOnePad = xboxOne;
  70606. return _this;
  70607. }
  70608. /**
  70609. * Defines the callback to call when left trigger is pressed
  70610. * @param callback defines the callback to use
  70611. */
  70612. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  70613. this._onlefttriggerchanged = callback;
  70614. };
  70615. /**
  70616. * Defines the callback to call when right trigger is pressed
  70617. * @param callback defines the callback to use
  70618. */
  70619. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  70620. this._onrighttriggerchanged = callback;
  70621. };
  70622. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  70623. /**
  70624. * Gets or sets left trigger value
  70625. */
  70626. get: function () {
  70627. return this._leftTrigger;
  70628. },
  70629. set: function (newValue) {
  70630. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  70631. this._onlefttriggerchanged(newValue);
  70632. }
  70633. this._leftTrigger = newValue;
  70634. },
  70635. enumerable: true,
  70636. configurable: true
  70637. });
  70638. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  70639. /**
  70640. * Gets or sets right trigger value
  70641. */
  70642. get: function () {
  70643. return this._rightTrigger;
  70644. },
  70645. set: function (newValue) {
  70646. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  70647. this._onrighttriggerchanged(newValue);
  70648. }
  70649. this._rightTrigger = newValue;
  70650. },
  70651. enumerable: true,
  70652. configurable: true
  70653. });
  70654. /**
  70655. * Defines the callback to call when a button is pressed
  70656. * @param callback defines the callback to use
  70657. */
  70658. Xbox360Pad.prototype.onbuttondown = function (callback) {
  70659. this._onbuttondown = callback;
  70660. };
  70661. /**
  70662. * Defines the callback to call when a button is released
  70663. * @param callback defines the callback to use
  70664. */
  70665. Xbox360Pad.prototype.onbuttonup = function (callback) {
  70666. this._onbuttonup = callback;
  70667. };
  70668. /**
  70669. * Defines the callback to call when a pad is pressed
  70670. * @param callback defines the callback to use
  70671. */
  70672. Xbox360Pad.prototype.ondpaddown = function (callback) {
  70673. this._ondpaddown = callback;
  70674. };
  70675. /**
  70676. * Defines the callback to call when a pad is released
  70677. * @param callback defines the callback to use
  70678. */
  70679. Xbox360Pad.prototype.ondpadup = function (callback) {
  70680. this._ondpadup = callback;
  70681. };
  70682. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  70683. if (newValue !== currentValue) {
  70684. if (newValue === 1) {
  70685. if (this._onbuttondown) {
  70686. this._onbuttondown(buttonType);
  70687. }
  70688. this.onButtonDownObservable.notifyObservers(buttonType);
  70689. }
  70690. if (newValue === 0) {
  70691. if (this._onbuttonup) {
  70692. this._onbuttonup(buttonType);
  70693. }
  70694. this.onButtonUpObservable.notifyObservers(buttonType);
  70695. }
  70696. }
  70697. return newValue;
  70698. };
  70699. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  70700. if (newValue !== currentValue) {
  70701. if (newValue === 1) {
  70702. if (this._ondpaddown) {
  70703. this._ondpaddown(buttonType);
  70704. }
  70705. this.onPadDownObservable.notifyObservers(buttonType);
  70706. }
  70707. if (newValue === 0) {
  70708. if (this._ondpadup) {
  70709. this._ondpadup(buttonType);
  70710. }
  70711. this.onPadUpObservable.notifyObservers(buttonType);
  70712. }
  70713. }
  70714. return newValue;
  70715. };
  70716. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  70717. /** Gets or sets value of A button */
  70718. get: function () {
  70719. return this._buttonA;
  70720. },
  70721. set: function (value) {
  70722. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  70723. },
  70724. enumerable: true,
  70725. configurable: true
  70726. });
  70727. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  70728. /** Gets or sets value of B button */
  70729. get: function () {
  70730. return this._buttonB;
  70731. },
  70732. set: function (value) {
  70733. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  70734. },
  70735. enumerable: true,
  70736. configurable: true
  70737. });
  70738. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  70739. /** Gets or sets value of X button */
  70740. get: function () {
  70741. return this._buttonX;
  70742. },
  70743. set: function (value) {
  70744. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  70745. },
  70746. enumerable: true,
  70747. configurable: true
  70748. });
  70749. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  70750. /** Gets or sets value of Y button */
  70751. get: function () {
  70752. return this._buttonY;
  70753. },
  70754. set: function (value) {
  70755. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  70756. },
  70757. enumerable: true,
  70758. configurable: true
  70759. });
  70760. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  70761. /** Gets or sets value of Start button */
  70762. get: function () {
  70763. return this._buttonStart;
  70764. },
  70765. set: function (value) {
  70766. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  70767. },
  70768. enumerable: true,
  70769. configurable: true
  70770. });
  70771. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  70772. /** Gets or sets value of Back button */
  70773. get: function () {
  70774. return this._buttonBack;
  70775. },
  70776. set: function (value) {
  70777. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  70778. },
  70779. enumerable: true,
  70780. configurable: true
  70781. });
  70782. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  70783. /** Gets or sets value of Left button */
  70784. get: function () {
  70785. return this._buttonLB;
  70786. },
  70787. set: function (value) {
  70788. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  70789. },
  70790. enumerable: true,
  70791. configurable: true
  70792. });
  70793. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  70794. /** Gets or sets value of Right button */
  70795. get: function () {
  70796. return this._buttonRB;
  70797. },
  70798. set: function (value) {
  70799. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  70800. },
  70801. enumerable: true,
  70802. configurable: true
  70803. });
  70804. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  70805. /** Gets or sets value of left stick */
  70806. get: function () {
  70807. return this._buttonLeftStick;
  70808. },
  70809. set: function (value) {
  70810. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  70811. },
  70812. enumerable: true,
  70813. configurable: true
  70814. });
  70815. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  70816. /** Gets or sets value of right stick */
  70817. get: function () {
  70818. return this._buttonRightStick;
  70819. },
  70820. set: function (value) {
  70821. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  70822. },
  70823. enumerable: true,
  70824. configurable: true
  70825. });
  70826. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  70827. /** Gets or sets value of DPad up */
  70828. get: function () {
  70829. return this._dPadUp;
  70830. },
  70831. set: function (value) {
  70832. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  70833. },
  70834. enumerable: true,
  70835. configurable: true
  70836. });
  70837. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  70838. /** Gets or sets value of DPad down */
  70839. get: function () {
  70840. return this._dPadDown;
  70841. },
  70842. set: function (value) {
  70843. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  70844. },
  70845. enumerable: true,
  70846. configurable: true
  70847. });
  70848. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  70849. /** Gets or sets value of DPad left */
  70850. get: function () {
  70851. return this._dPadLeft;
  70852. },
  70853. set: function (value) {
  70854. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  70855. },
  70856. enumerable: true,
  70857. configurable: true
  70858. });
  70859. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  70860. /** Gets or sets value of DPad right */
  70861. get: function () {
  70862. return this._dPadRight;
  70863. },
  70864. set: function (value) {
  70865. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  70866. },
  70867. enumerable: true,
  70868. configurable: true
  70869. });
  70870. /**
  70871. * Force the gamepad to synchronize with device values
  70872. */
  70873. Xbox360Pad.prototype.update = function () {
  70874. _super.prototype.update.call(this);
  70875. if (this._isXboxOnePad) {
  70876. this.buttonA = this.browserGamepad.buttons[0].value;
  70877. this.buttonB = this.browserGamepad.buttons[1].value;
  70878. this.buttonX = this.browserGamepad.buttons[2].value;
  70879. this.buttonY = this.browserGamepad.buttons[3].value;
  70880. this.buttonLB = this.browserGamepad.buttons[4].value;
  70881. this.buttonRB = this.browserGamepad.buttons[5].value;
  70882. this.leftTrigger = this.browserGamepad.axes[2];
  70883. this.rightTrigger = this.browserGamepad.axes[5];
  70884. this.buttonBack = this.browserGamepad.buttons[9].value;
  70885. this.buttonStart = this.browserGamepad.buttons[8].value;
  70886. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  70887. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  70888. this.dPadUp = this.browserGamepad.buttons[11].value;
  70889. this.dPadDown = this.browserGamepad.buttons[12].value;
  70890. this.dPadLeft = this.browserGamepad.buttons[13].value;
  70891. this.dPadRight = this.browserGamepad.buttons[14].value;
  70892. }
  70893. else {
  70894. this.buttonA = this.browserGamepad.buttons[0].value;
  70895. this.buttonB = this.browserGamepad.buttons[1].value;
  70896. this.buttonX = this.browserGamepad.buttons[2].value;
  70897. this.buttonY = this.browserGamepad.buttons[3].value;
  70898. this.buttonLB = this.browserGamepad.buttons[4].value;
  70899. this.buttonRB = this.browserGamepad.buttons[5].value;
  70900. this.leftTrigger = this.browserGamepad.buttons[6].value;
  70901. this.rightTrigger = this.browserGamepad.buttons[7].value;
  70902. this.buttonBack = this.browserGamepad.buttons[8].value;
  70903. this.buttonStart = this.browserGamepad.buttons[9].value;
  70904. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  70905. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  70906. this.dPadUp = this.browserGamepad.buttons[12].value;
  70907. this.dPadDown = this.browserGamepad.buttons[13].value;
  70908. this.dPadLeft = this.browserGamepad.buttons[14].value;
  70909. this.dPadRight = this.browserGamepad.buttons[15].value;
  70910. }
  70911. };
  70912. Xbox360Pad.prototype.dispose = function () {
  70913. _super.prototype.dispose.call(this);
  70914. this.onButtonDownObservable.clear();
  70915. this.onButtonUpObservable.clear();
  70916. this.onPadDownObservable.clear();
  70917. this.onPadUpObservable.clear();
  70918. };
  70919. return Xbox360Pad;
  70920. }(BABYLON.Gamepad));
  70921. BABYLON.Xbox360Pad = Xbox360Pad;
  70922. })(BABYLON || (BABYLON = {}));
  70923. //# sourceMappingURL=babylon.xboxGamepad.js.map
  70924. var BABYLON;
  70925. (function (BABYLON) {
  70926. /**
  70927. * Defines the types of pose enabled controllers that are supported
  70928. */
  70929. var PoseEnabledControllerType;
  70930. (function (PoseEnabledControllerType) {
  70931. /**
  70932. * HTC Vive
  70933. */
  70934. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  70935. /**
  70936. * Oculus Rift
  70937. */
  70938. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  70939. /**
  70940. * Windows mixed reality
  70941. */
  70942. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  70943. /**
  70944. * Samsung gear VR
  70945. */
  70946. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  70947. /**
  70948. * Google Daydream
  70949. */
  70950. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  70951. /**
  70952. * Generic
  70953. */
  70954. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  70955. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  70956. /**
  70957. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  70958. */
  70959. var PoseEnabledControllerHelper = /** @class */ (function () {
  70960. function PoseEnabledControllerHelper() {
  70961. }
  70962. /**
  70963. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  70964. * @param vrGamepad the gamepad to initialized
  70965. * @returns a vr controller of the type the gamepad identified as
  70966. */
  70967. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  70968. // Oculus Touch
  70969. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  70970. return new BABYLON.OculusTouchController(vrGamepad);
  70971. }
  70972. // Windows Mixed Reality controllers
  70973. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  70974. return new BABYLON.WindowsMotionController(vrGamepad);
  70975. }
  70976. // HTC Vive
  70977. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  70978. return new BABYLON.ViveController(vrGamepad);
  70979. }
  70980. // Samsung/Oculus Gear VR
  70981. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  70982. return new BABYLON.GearVRController(vrGamepad);
  70983. }
  70984. // Google Daydream
  70985. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  70986. return new BABYLON.DaydreamController(vrGamepad);
  70987. }
  70988. // Generic
  70989. else {
  70990. return new BABYLON.GenericController(vrGamepad);
  70991. }
  70992. };
  70993. return PoseEnabledControllerHelper;
  70994. }());
  70995. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  70996. /**
  70997. * Defines the PoseEnabledController object that contains state of a vr capable controller
  70998. */
  70999. var PoseEnabledController = /** @class */ (function (_super) {
  71000. __extends(PoseEnabledController, _super);
  71001. /**
  71002. * Creates a new PoseEnabledController from a gamepad
  71003. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  71004. */
  71005. function PoseEnabledController(browserGamepad) {
  71006. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  71007. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  71008. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  71009. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  71010. /**
  71011. * The device position in babylon space
  71012. */
  71013. _this.devicePosition = BABYLON.Vector3.Zero();
  71014. /**
  71015. * The device rotation in babylon space
  71016. */
  71017. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  71018. /**
  71019. * The scale factor of the device in babylon space
  71020. */
  71021. _this.deviceScaleFactor = 1;
  71022. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  71023. /**
  71024. * Internal, matrix used to convert room space to babylon space
  71025. */
  71026. _this._deviceToWorld = BABYLON.Matrix.Identity();
  71027. /**
  71028. * Node to be used when casting a ray from the controller
  71029. */
  71030. _this._pointingPoseNode = null;
  71031. _this._workingMatrix = BABYLON.Matrix.Identity();
  71032. /**
  71033. * @hidden
  71034. */
  71035. _this._meshAttachedObservable = new BABYLON.Observable();
  71036. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  71037. _this.controllerType = PoseEnabledControllerType.GENERIC;
  71038. _this.position = BABYLON.Vector3.Zero();
  71039. _this.rotationQuaternion = new BABYLON.Quaternion();
  71040. _this._calculatedPosition = BABYLON.Vector3.Zero();
  71041. _this._calculatedRotation = new BABYLON.Quaternion();
  71042. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  71043. return _this;
  71044. }
  71045. /**
  71046. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  71047. */
  71048. PoseEnabledController.prototype.update = function () {
  71049. _super.prototype.update.call(this);
  71050. var pose = this.browserGamepad.pose;
  71051. this.updateFromDevice(pose);
  71052. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  71053. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  71054. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  71055. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  71056. if (this._mesh) {
  71057. this._mesh.position.copyFrom(this.devicePosition);
  71058. if (this._mesh.rotationQuaternion) {
  71059. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  71060. }
  71061. }
  71062. };
  71063. /**
  71064. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  71065. * @param poseData raw pose fromthe device
  71066. */
  71067. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  71068. if (poseData) {
  71069. this.rawPose = poseData;
  71070. if (poseData.position) {
  71071. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  71072. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  71073. this._deviceRoomPosition.z *= -1;
  71074. }
  71075. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  71076. this._calculatedPosition.addInPlace(this.position);
  71077. }
  71078. var pose = this.rawPose;
  71079. if (poseData.orientation && pose.orientation) {
  71080. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  71081. if (this._mesh) {
  71082. if (this._mesh.getScene().useRightHandedSystem) {
  71083. this._deviceRoomRotationQuaternion.z *= -1;
  71084. this._deviceRoomRotationQuaternion.w *= -1;
  71085. }
  71086. else {
  71087. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  71088. }
  71089. }
  71090. // if the camera is set, rotate to the camera's rotation
  71091. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  71092. }
  71093. }
  71094. };
  71095. /**
  71096. * Attaches a mesh to the controller
  71097. * @param mesh the mesh to be attached
  71098. */
  71099. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  71100. if (this._mesh) {
  71101. this._mesh.parent = null;
  71102. }
  71103. this._mesh = mesh;
  71104. if (this._poseControlledCamera) {
  71105. this._mesh.parent = this._poseControlledCamera;
  71106. }
  71107. if (!this._mesh.rotationQuaternion) {
  71108. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  71109. }
  71110. this._meshAttachedObservable.notifyObservers(mesh);
  71111. };
  71112. /**
  71113. * Attaches the controllers mesh to a camera
  71114. * @param camera the camera the mesh should be attached to
  71115. */
  71116. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  71117. this._poseControlledCamera = camera;
  71118. if (this._mesh) {
  71119. this._mesh.parent = this._poseControlledCamera;
  71120. }
  71121. };
  71122. /**
  71123. * Disposes of the controller
  71124. */
  71125. PoseEnabledController.prototype.dispose = function () {
  71126. if (this._mesh) {
  71127. this._mesh.dispose();
  71128. }
  71129. this._mesh = null;
  71130. _super.prototype.dispose.call(this);
  71131. };
  71132. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  71133. /**
  71134. * The mesh that is attached to the controller
  71135. */
  71136. get: function () {
  71137. return this._mesh;
  71138. },
  71139. enumerable: true,
  71140. configurable: true
  71141. });
  71142. /**
  71143. * Gets the ray of the controller in the direction the controller is pointing
  71144. * @param length the length the resulting ray should be
  71145. * @returns a ray in the direction the controller is pointing
  71146. */
  71147. PoseEnabledController.prototype.getForwardRay = function (length) {
  71148. if (length === void 0) { length = 100; }
  71149. if (!this.mesh) {
  71150. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  71151. }
  71152. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  71153. var origin = m.getTranslation();
  71154. var forward = new BABYLON.Vector3(0, 0, -1);
  71155. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  71156. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  71157. return new BABYLON.Ray(origin, direction, length);
  71158. };
  71159. /**
  71160. * Name of the child mesh that can be used to cast a ray from the controller
  71161. */
  71162. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  71163. return PoseEnabledController;
  71164. }(BABYLON.Gamepad));
  71165. BABYLON.PoseEnabledController = PoseEnabledController;
  71166. })(BABYLON || (BABYLON = {}));
  71167. //# sourceMappingURL=babylon.poseEnabledController.js.map
  71168. var BABYLON;
  71169. (function (BABYLON) {
  71170. /**
  71171. * Defines the WebVRController object that represents controllers tracked in 3D space
  71172. */
  71173. var WebVRController = /** @class */ (function (_super) {
  71174. __extends(WebVRController, _super);
  71175. /**
  71176. * Creates a new WebVRController from a gamepad
  71177. * @param vrGamepad the gamepad that the WebVRController should be created from
  71178. */
  71179. function WebVRController(vrGamepad) {
  71180. var _this = _super.call(this, vrGamepad) || this;
  71181. // Observables
  71182. /**
  71183. * Fired when the trigger state has changed
  71184. */
  71185. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  71186. /**
  71187. * Fired when the main button state has changed
  71188. */
  71189. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  71190. /**
  71191. * Fired when the secondary button state has changed
  71192. */
  71193. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  71194. /**
  71195. * Fired when the pad state has changed
  71196. */
  71197. _this.onPadStateChangedObservable = new BABYLON.Observable();
  71198. /**
  71199. * Fired when controllers stick values have changed
  71200. */
  71201. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  71202. /**
  71203. * X and Y axis corrisponding to the controllers joystick
  71204. */
  71205. _this.pad = { x: 0, y: 0 };
  71206. // avoid GC, store state in a tmp object
  71207. _this._changes = {
  71208. pressChanged: false,
  71209. touchChanged: false,
  71210. valueChanged: false,
  71211. changed: false
  71212. };
  71213. _this._buttons = new Array(vrGamepad.buttons.length);
  71214. _this.hand = vrGamepad.hand;
  71215. return _this;
  71216. }
  71217. /**
  71218. * Fired when a controller button's state has changed
  71219. * @param callback the callback containing the button that was modified
  71220. */
  71221. WebVRController.prototype.onButtonStateChange = function (callback) {
  71222. this._onButtonStateChange = callback;
  71223. };
  71224. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  71225. /**
  71226. * The default controller model for the controller
  71227. */
  71228. get: function () {
  71229. return this._defaultModel;
  71230. },
  71231. enumerable: true,
  71232. configurable: true
  71233. });
  71234. /**
  71235. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  71236. */
  71237. WebVRController.prototype.update = function () {
  71238. _super.prototype.update.call(this);
  71239. for (var index = 0; index < this._buttons.length; index++) {
  71240. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  71241. }
  71242. ;
  71243. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  71244. this.pad.x = this.leftStick.x;
  71245. this.pad.y = this.leftStick.y;
  71246. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  71247. }
  71248. };
  71249. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  71250. if (!newState) {
  71251. newState = {
  71252. pressed: false,
  71253. touched: false,
  71254. value: 0
  71255. };
  71256. }
  71257. if (!currentState) {
  71258. this._buttons[buttonIndex] = {
  71259. pressed: newState.pressed,
  71260. touched: newState.touched,
  71261. value: newState.value
  71262. };
  71263. return;
  71264. }
  71265. this._checkChanges(newState, currentState);
  71266. if (this._changes.changed) {
  71267. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  71268. this._handleButtonChange(buttonIndex, newState, this._changes);
  71269. }
  71270. this._buttons[buttonIndex].pressed = newState.pressed;
  71271. this._buttons[buttonIndex].touched = newState.touched;
  71272. // oculus triggers are never 0, thou not touched.
  71273. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  71274. };
  71275. WebVRController.prototype._checkChanges = function (newState, currentState) {
  71276. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  71277. this._changes.touchChanged = newState.touched !== currentState.touched;
  71278. this._changes.valueChanged = newState.value !== currentState.value;
  71279. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  71280. return this._changes;
  71281. };
  71282. /**
  71283. * Disposes of th webVRCOntroller
  71284. */
  71285. WebVRController.prototype.dispose = function () {
  71286. _super.prototype.dispose.call(this);
  71287. this.onTriggerStateChangedObservable.clear();
  71288. this.onMainButtonStateChangedObservable.clear();
  71289. this.onSecondaryButtonStateChangedObservable.clear();
  71290. this.onPadStateChangedObservable.clear();
  71291. this.onPadValuesChangedObservable.clear();
  71292. };
  71293. return WebVRController;
  71294. }(BABYLON.PoseEnabledController));
  71295. BABYLON.WebVRController = WebVRController;
  71296. })(BABYLON || (BABYLON = {}));
  71297. //# sourceMappingURL=babylon.webVRController.js.map
  71298. var BABYLON;
  71299. (function (BABYLON) {
  71300. /**
  71301. * Oculus Touch Controller
  71302. */
  71303. var OculusTouchController = /** @class */ (function (_super) {
  71304. __extends(OculusTouchController, _super);
  71305. /**
  71306. * Creates a new OculusTouchController from a gamepad
  71307. * @param vrGamepad the gamepad that the controller should be created from
  71308. */
  71309. function OculusTouchController(vrGamepad) {
  71310. var _this = _super.call(this, vrGamepad) || this;
  71311. /**
  71312. * Fired when the secondary trigger on this controller is modified
  71313. */
  71314. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  71315. /**
  71316. * Fired when the thumb rest on this controller is modified
  71317. */
  71318. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  71319. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  71320. return _this;
  71321. }
  71322. /**
  71323. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71324. * @param scene scene in which to add meshes
  71325. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71326. */
  71327. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71328. var _this = this;
  71329. var meshName;
  71330. // Hand
  71331. if (this.hand === 'left') {
  71332. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  71333. }
  71334. else { // Right is the default if no hand is specified
  71335. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  71336. }
  71337. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  71338. /*
  71339. Parent Mesh name: oculus_touch_left
  71340. - body
  71341. - trigger
  71342. - thumbstick
  71343. - grip
  71344. - button_y
  71345. - button_x
  71346. - button_enter
  71347. */
  71348. _this._defaultModel = newMeshes[1];
  71349. _this.attachToMesh(_this._defaultModel);
  71350. if (meshLoaded) {
  71351. meshLoaded(_this._defaultModel);
  71352. }
  71353. });
  71354. };
  71355. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  71356. /**
  71357. * Fired when the A button on this controller is modified
  71358. */
  71359. get: function () {
  71360. if (this.hand === 'right') {
  71361. return this.onMainButtonStateChangedObservable;
  71362. }
  71363. else {
  71364. throw new Error('No A button on left hand');
  71365. }
  71366. },
  71367. enumerable: true,
  71368. configurable: true
  71369. });
  71370. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  71371. /**
  71372. * Fired when the B button on this controller is modified
  71373. */
  71374. get: function () {
  71375. if (this.hand === 'right') {
  71376. return this.onSecondaryButtonStateChangedObservable;
  71377. }
  71378. else {
  71379. throw new Error('No B button on left hand');
  71380. }
  71381. },
  71382. enumerable: true,
  71383. configurable: true
  71384. });
  71385. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  71386. /**
  71387. * Fired when the X button on this controller is modified
  71388. */
  71389. get: function () {
  71390. if (this.hand === 'left') {
  71391. return this.onMainButtonStateChangedObservable;
  71392. }
  71393. else {
  71394. throw new Error('No X button on right hand');
  71395. }
  71396. },
  71397. enumerable: true,
  71398. configurable: true
  71399. });
  71400. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  71401. /**
  71402. * Fired when the Y button on this controller is modified
  71403. */
  71404. get: function () {
  71405. if (this.hand === 'left') {
  71406. return this.onSecondaryButtonStateChangedObservable;
  71407. }
  71408. else {
  71409. throw new Error('No Y button on right hand');
  71410. }
  71411. },
  71412. enumerable: true,
  71413. configurable: true
  71414. });
  71415. /**
  71416. * Called once for each button that changed state since the last frame
  71417. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  71418. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  71419. * 2) secondary trigger (same)
  71420. * 3) A (right) X (left), touch, pressed = value
  71421. * 4) B / Y
  71422. * 5) thumb rest
  71423. * @param buttonIdx Which button index changed
  71424. * @param state New state of the button
  71425. * @param changes Which properties on the state changed since last frame
  71426. */
  71427. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71428. var notifyObject = state; //{ state: state, changes: changes };
  71429. var triggerDirection = this.hand === 'right' ? -1 : 1;
  71430. switch (buttonIdx) {
  71431. case 0:
  71432. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  71433. return;
  71434. case 1: // index trigger
  71435. if (this._defaultModel) {
  71436. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  71437. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  71438. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  71439. }
  71440. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  71441. return;
  71442. case 2: // secondary trigger
  71443. if (this._defaultModel) {
  71444. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  71445. }
  71446. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  71447. return;
  71448. case 3:
  71449. if (this._defaultModel) {
  71450. if (notifyObject.pressed) {
  71451. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  71452. }
  71453. else {
  71454. (this._defaultModel.getChildren()[1]).position.y = 0;
  71455. }
  71456. }
  71457. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  71458. return;
  71459. case 4:
  71460. if (this._defaultModel) {
  71461. if (notifyObject.pressed) {
  71462. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  71463. }
  71464. else {
  71465. (this._defaultModel.getChildren()[2]).position.y = 0;
  71466. }
  71467. }
  71468. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  71469. return;
  71470. case 5:
  71471. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  71472. return;
  71473. }
  71474. };
  71475. /**
  71476. * Base Url for the controller model.
  71477. */
  71478. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  71479. /**
  71480. * File name for the left controller model.
  71481. */
  71482. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  71483. /**
  71484. * File name for the right controller model.
  71485. */
  71486. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  71487. return OculusTouchController;
  71488. }(BABYLON.WebVRController));
  71489. BABYLON.OculusTouchController = OculusTouchController;
  71490. })(BABYLON || (BABYLON = {}));
  71491. //# sourceMappingURL=babylon.oculusTouchController.js.map
  71492. var BABYLON;
  71493. (function (BABYLON) {
  71494. /**
  71495. * Vive Controller
  71496. */
  71497. var ViveController = /** @class */ (function (_super) {
  71498. __extends(ViveController, _super);
  71499. /**
  71500. * Creates a new ViveController from a gamepad
  71501. * @param vrGamepad the gamepad that the controller should be created from
  71502. */
  71503. function ViveController(vrGamepad) {
  71504. var _this = _super.call(this, vrGamepad) || this;
  71505. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  71506. _this._invertLeftStickY = true;
  71507. return _this;
  71508. }
  71509. /**
  71510. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71511. * @param scene scene in which to add meshes
  71512. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71513. */
  71514. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71515. var _this = this;
  71516. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  71517. /*
  71518. Parent Mesh name: ViveWand
  71519. - body
  71520. - r_gripper
  71521. - l_gripper
  71522. - menu_button
  71523. - system_button
  71524. - trackpad
  71525. - trigger
  71526. - LED
  71527. */
  71528. _this._defaultModel = newMeshes[1];
  71529. _this.attachToMesh(_this._defaultModel);
  71530. if (meshLoaded) {
  71531. meshLoaded(_this._defaultModel);
  71532. }
  71533. });
  71534. };
  71535. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  71536. /**
  71537. * Fired when the left button on this controller is modified
  71538. */
  71539. get: function () {
  71540. return this.onMainButtonStateChangedObservable;
  71541. },
  71542. enumerable: true,
  71543. configurable: true
  71544. });
  71545. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  71546. /**
  71547. * Fired when the right button on this controller is modified
  71548. */
  71549. get: function () {
  71550. return this.onMainButtonStateChangedObservable;
  71551. },
  71552. enumerable: true,
  71553. configurable: true
  71554. });
  71555. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  71556. /**
  71557. * Fired when the menu button on this controller is modified
  71558. */
  71559. get: function () {
  71560. return this.onSecondaryButtonStateChangedObservable;
  71561. },
  71562. enumerable: true,
  71563. configurable: true
  71564. });
  71565. /**
  71566. * Called once for each button that changed state since the last frame
  71567. * Vive mapping:
  71568. * 0: touchpad
  71569. * 1: trigger
  71570. * 2: left AND right buttons
  71571. * 3: menu button
  71572. * @param buttonIdx Which button index changed
  71573. * @param state New state of the button
  71574. * @param changes Which properties on the state changed since last frame
  71575. */
  71576. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71577. var notifyObject = state; //{ state: state, changes: changes };
  71578. switch (buttonIdx) {
  71579. case 0:
  71580. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  71581. return;
  71582. case 1: // index trigger
  71583. if (this._defaultModel) {
  71584. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  71585. }
  71586. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  71587. return;
  71588. case 2: // left AND right button
  71589. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  71590. return;
  71591. case 3:
  71592. if (this._defaultModel) {
  71593. if (notifyObject.pressed) {
  71594. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  71595. }
  71596. else {
  71597. (this._defaultModel.getChildren()[2]).position.y = 0;
  71598. }
  71599. }
  71600. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  71601. return;
  71602. }
  71603. };
  71604. /**
  71605. * Base Url for the controller model.
  71606. */
  71607. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  71608. /**
  71609. * File name for the controller model.
  71610. */
  71611. ViveController.MODEL_FILENAME = 'wand.babylon';
  71612. return ViveController;
  71613. }(BABYLON.WebVRController));
  71614. BABYLON.ViveController = ViveController;
  71615. })(BABYLON || (BABYLON = {}));
  71616. //# sourceMappingURL=babylon.viveController.js.map
  71617. var BABYLON;
  71618. (function (BABYLON) {
  71619. /**
  71620. * Generic Controller
  71621. */
  71622. var GenericController = /** @class */ (function (_super) {
  71623. __extends(GenericController, _super);
  71624. /**
  71625. * Creates a new GenericController from a gamepad
  71626. * @param vrGamepad the gamepad that the controller should be created from
  71627. */
  71628. function GenericController(vrGamepad) {
  71629. return _super.call(this, vrGamepad) || this;
  71630. }
  71631. /**
  71632. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71633. * @param scene scene in which to add meshes
  71634. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71635. */
  71636. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71637. var _this = this;
  71638. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  71639. _this._defaultModel = newMeshes[1];
  71640. _this.attachToMesh(_this._defaultModel);
  71641. if (meshLoaded) {
  71642. meshLoaded(_this._defaultModel);
  71643. }
  71644. });
  71645. };
  71646. /**
  71647. * Called once for each button that changed state since the last frame
  71648. * @param buttonIdx Which button index changed
  71649. * @param state New state of the button
  71650. * @param changes Which properties on the state changed since last frame
  71651. */
  71652. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71653. console.log("Button id: " + buttonIdx + "state: ");
  71654. console.dir(state);
  71655. };
  71656. /**
  71657. * Base Url for the controller model.
  71658. */
  71659. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  71660. /**
  71661. * File name for the controller model.
  71662. */
  71663. GenericController.MODEL_FILENAME = 'generic.babylon';
  71664. return GenericController;
  71665. }(BABYLON.WebVRController));
  71666. BABYLON.GenericController = GenericController;
  71667. })(BABYLON || (BABYLON = {}));
  71668. //# sourceMappingURL=babylon.genericController.js.map
  71669. var BABYLON;
  71670. (function (BABYLON) {
  71671. /**
  71672. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  71673. */
  71674. var LoadedMeshInfo = /** @class */ (function () {
  71675. function LoadedMeshInfo() {
  71676. /**
  71677. * Map of the button meshes contained in the controller
  71678. */
  71679. this.buttonMeshes = {};
  71680. /**
  71681. * Map of the axis meshes contained in the controller
  71682. */
  71683. this.axisMeshes = {};
  71684. }
  71685. return LoadedMeshInfo;
  71686. }());
  71687. /**
  71688. * Defines the WindowsMotionController object that the state of the windows motion controller
  71689. */
  71690. var WindowsMotionController = /** @class */ (function (_super) {
  71691. __extends(WindowsMotionController, _super);
  71692. /**
  71693. * Creates a new WindowsMotionController from a gamepad
  71694. * @param vrGamepad the gamepad that the controller should be created from
  71695. */
  71696. function WindowsMotionController(vrGamepad) {
  71697. var _this = _super.call(this, vrGamepad) || this;
  71698. _this._mapping = {
  71699. // Semantic button names
  71700. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  71701. // A mapping of the button name to glTF model node name
  71702. // that should be transformed by button value.
  71703. buttonMeshNames: {
  71704. 'trigger': 'SELECT',
  71705. 'menu': 'MENU',
  71706. 'grip': 'GRASP',
  71707. 'thumbstick': 'THUMBSTICK_PRESS',
  71708. 'trackpad': 'TOUCHPAD_PRESS'
  71709. },
  71710. // This mapping is used to translate from the Motion Controller to Babylon semantics
  71711. buttonObservableNames: {
  71712. 'trigger': 'onTriggerStateChangedObservable',
  71713. 'menu': 'onSecondaryButtonStateChangedObservable',
  71714. 'grip': 'onMainButtonStateChangedObservable',
  71715. 'thumbstick': 'onPadStateChangedObservable',
  71716. 'trackpad': 'onTrackpadChangedObservable'
  71717. },
  71718. // A mapping of the axis name to glTF model node name
  71719. // that should be transformed by axis value.
  71720. // This array mirrors the browserGamepad.axes array, such that
  71721. // the mesh corresponding to axis 0 is in this array index 0.
  71722. axisMeshNames: [
  71723. 'THUMBSTICK_X',
  71724. 'THUMBSTICK_Y',
  71725. 'TOUCHPAD_TOUCH_X',
  71726. 'TOUCHPAD_TOUCH_Y'
  71727. ],
  71728. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  71729. };
  71730. /**
  71731. * Fired when the trackpad on this controller is clicked
  71732. */
  71733. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  71734. /**
  71735. * Fired when the trackpad on this controller is modified
  71736. */
  71737. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  71738. /**
  71739. * The current x and y values of this controller's trackpad
  71740. */
  71741. _this.trackpad = { x: 0, y: 0 };
  71742. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  71743. _this._loadedMeshInfo = null;
  71744. return _this;
  71745. }
  71746. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  71747. /**
  71748. * Fired when the trigger on this controller is modified
  71749. */
  71750. get: function () {
  71751. return this.onTriggerStateChangedObservable;
  71752. },
  71753. enumerable: true,
  71754. configurable: true
  71755. });
  71756. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  71757. /**
  71758. * Fired when the menu button on this controller is modified
  71759. */
  71760. get: function () {
  71761. return this.onSecondaryButtonStateChangedObservable;
  71762. },
  71763. enumerable: true,
  71764. configurable: true
  71765. });
  71766. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  71767. /**
  71768. * Fired when the grip button on this controller is modified
  71769. */
  71770. get: function () {
  71771. return this.onMainButtonStateChangedObservable;
  71772. },
  71773. enumerable: true,
  71774. configurable: true
  71775. });
  71776. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  71777. /**
  71778. * Fired when the thumbstick button on this controller is modified
  71779. */
  71780. get: function () {
  71781. return this.onPadStateChangedObservable;
  71782. },
  71783. enumerable: true,
  71784. configurable: true
  71785. });
  71786. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  71787. /**
  71788. * Fired when the touchpad button on this controller is modified
  71789. */
  71790. get: function () {
  71791. return this.onTrackpadChangedObservable;
  71792. },
  71793. enumerable: true,
  71794. configurable: true
  71795. });
  71796. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  71797. /**
  71798. * Fired when the touchpad values on this controller are modified
  71799. */
  71800. get: function () {
  71801. return this.onTrackpadValuesChangedObservable;
  71802. },
  71803. enumerable: true,
  71804. configurable: true
  71805. });
  71806. /**
  71807. * Called once per frame by the engine.
  71808. */
  71809. WindowsMotionController.prototype.update = function () {
  71810. _super.prototype.update.call(this);
  71811. if (this.browserGamepad.axes) {
  71812. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  71813. this.trackpad.x = this.browserGamepad["axes"][2];
  71814. this.trackpad.y = this.browserGamepad["axes"][3];
  71815. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  71816. }
  71817. // Only need to animate axes if there is a loaded mesh
  71818. if (this._loadedMeshInfo) {
  71819. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  71820. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  71821. }
  71822. }
  71823. }
  71824. };
  71825. /**
  71826. * Called once for each button that changed state since the last frame
  71827. * @param buttonIdx Which button index changed
  71828. * @param state New state of the button
  71829. * @param changes Which properties on the state changed since last frame
  71830. */
  71831. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71832. var buttonName = this._mapping.buttons[buttonIdx];
  71833. if (!buttonName) {
  71834. return;
  71835. }
  71836. // Only emit events for buttons that we know how to map from index to name
  71837. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  71838. if (observable) {
  71839. observable.notifyObservers(state);
  71840. }
  71841. this._lerpButtonTransform(buttonName, state.value);
  71842. };
  71843. /**
  71844. * Moves the buttons on the controller mesh based on their current state
  71845. * @param buttonName the name of the button to move
  71846. * @param buttonValue the value of the button which determines the buttons new position
  71847. */
  71848. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  71849. // If there is no loaded mesh, there is nothing to transform.
  71850. if (!this._loadedMeshInfo) {
  71851. return;
  71852. }
  71853. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  71854. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  71855. return;
  71856. }
  71857. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  71858. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  71859. };
  71860. /**
  71861. * Moves the axis on the controller mesh based on its current state
  71862. * @param axis the index of the axis
  71863. * @param axisValue the value of the axis which determines the meshes new position
  71864. * @hidden
  71865. */
  71866. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  71867. if (!this._loadedMeshInfo) {
  71868. return;
  71869. }
  71870. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  71871. if (!meshInfo) {
  71872. return;
  71873. }
  71874. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  71875. return;
  71876. }
  71877. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  71878. var lerpValue = axisValue * 0.5 + 0.5;
  71879. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  71880. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  71881. };
  71882. /**
  71883. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71884. * @param scene scene in which to add meshes
  71885. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71886. */
  71887. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  71888. var _this = this;
  71889. if (forceDefault === void 0) { forceDefault = false; }
  71890. var path;
  71891. var filename;
  71892. // Checking if GLB loader is present
  71893. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  71894. // Determine the device specific folder based on the ID suffix
  71895. var device = 'default';
  71896. if (this.id && !forceDefault) {
  71897. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  71898. device = ((match && match[0]) || device);
  71899. }
  71900. // Hand
  71901. if (this.hand === 'left') {
  71902. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  71903. }
  71904. else { // Right is the default if no hand is specified
  71905. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  71906. }
  71907. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  71908. }
  71909. else {
  71910. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  71911. path = BABYLON.GenericController.MODEL_BASE_URL;
  71912. filename = BABYLON.GenericController.MODEL_FILENAME;
  71913. }
  71914. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  71915. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  71916. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  71917. if (!_this._loadedMeshInfo) {
  71918. return;
  71919. }
  71920. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  71921. _this.attachToMesh(_this._defaultModel);
  71922. if (meshLoaded) {
  71923. meshLoaded(_this._defaultModel);
  71924. }
  71925. }, null, function (scene, message) {
  71926. BABYLON.Tools.Log(message);
  71927. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  71928. if (!forceDefault) {
  71929. _this.initControllerMesh(scene, meshLoaded, true);
  71930. }
  71931. });
  71932. };
  71933. /**
  71934. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  71935. * can be transformed by button presses and axes values, based on this._mapping.
  71936. *
  71937. * @param scene scene in which the meshes exist
  71938. * @param meshes list of meshes that make up the controller model to process
  71939. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  71940. */
  71941. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  71942. var loadedMeshInfo = null;
  71943. // Create a new mesh to contain the glTF hierarchy
  71944. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  71945. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  71946. var childMesh = null;
  71947. for (var i = 0; i < meshes.length; i++) {
  71948. var mesh = meshes[i];
  71949. if (!mesh.parent) {
  71950. // Exclude controller meshes from picking results
  71951. mesh.isPickable = false;
  71952. // Handle root node, attach to the new parentMesh
  71953. childMesh = mesh;
  71954. break;
  71955. }
  71956. }
  71957. if (childMesh) {
  71958. childMesh.setParent(parentMesh);
  71959. // Create our mesh info. Note that this method will always return non-null.
  71960. loadedMeshInfo = this.createMeshInfo(parentMesh);
  71961. }
  71962. else {
  71963. BABYLON.Tools.Warn('Could not find root node in model file.');
  71964. }
  71965. return loadedMeshInfo;
  71966. };
  71967. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  71968. var loadedMeshInfo = new LoadedMeshInfo();
  71969. var i;
  71970. loadedMeshInfo.rootNode = rootNode;
  71971. // Reset the caches
  71972. loadedMeshInfo.buttonMeshes = {};
  71973. loadedMeshInfo.axisMeshes = {};
  71974. // Button Meshes
  71975. for (i = 0; i < this._mapping.buttons.length; i++) {
  71976. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  71977. if (!buttonMeshName) {
  71978. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  71979. continue;
  71980. }
  71981. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  71982. if (!buttonMesh) {
  71983. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  71984. continue;
  71985. }
  71986. var buttonMeshInfo = {
  71987. index: i,
  71988. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  71989. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  71990. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  71991. };
  71992. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  71993. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  71994. }
  71995. else {
  71996. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  71997. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  71998. '(VALUE: ' + !!buttonMeshInfo.value +
  71999. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  72000. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  72001. ')');
  72002. }
  72003. }
  72004. // Axis Meshes
  72005. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  72006. var axisMeshName = this._mapping.axisMeshNames[i];
  72007. if (!axisMeshName) {
  72008. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  72009. continue;
  72010. }
  72011. var axisMesh = getChildByName(rootNode, axisMeshName);
  72012. if (!axisMesh) {
  72013. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  72014. continue;
  72015. }
  72016. var axisMeshInfo = {
  72017. index: i,
  72018. value: getImmediateChildByName(axisMesh, 'VALUE'),
  72019. min: getImmediateChildByName(axisMesh, 'MIN'),
  72020. max: getImmediateChildByName(axisMesh, 'MAX')
  72021. };
  72022. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  72023. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  72024. }
  72025. else {
  72026. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  72027. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  72028. '(VALUE: ' + !!axisMeshInfo.value +
  72029. ', MIN: ' + !!axisMeshInfo.min +
  72030. ', MAX:' + !!axisMeshInfo.max +
  72031. ')');
  72032. }
  72033. }
  72034. // Pointing Ray
  72035. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  72036. if (!loadedMeshInfo.pointingPoseNode) {
  72037. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  72038. }
  72039. return loadedMeshInfo;
  72040. // Look through all children recursively. This will return null if no mesh exists with the given name.
  72041. function getChildByName(node, name) {
  72042. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  72043. }
  72044. // Look through only immediate children. This will return null if no mesh exists with the given name.
  72045. function getImmediateChildByName(node, name) {
  72046. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  72047. }
  72048. };
  72049. /**
  72050. * Gets the ray of the controller in the direction the controller is pointing
  72051. * @param length the length the resulting ray should be
  72052. * @returns a ray in the direction the controller is pointing
  72053. */
  72054. WindowsMotionController.prototype.getForwardRay = function (length) {
  72055. if (length === void 0) { length = 100; }
  72056. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  72057. return _super.prototype.getForwardRay.call(this, length);
  72058. }
  72059. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  72060. var origin = m.getTranslation();
  72061. var forward = new BABYLON.Vector3(0, 0, -1);
  72062. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  72063. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  72064. return new BABYLON.Ray(origin, direction, length);
  72065. };
  72066. /**
  72067. * Disposes of the controller
  72068. */
  72069. WindowsMotionController.prototype.dispose = function () {
  72070. _super.prototype.dispose.call(this);
  72071. this.onTrackpadChangedObservable.clear();
  72072. };
  72073. /**
  72074. * The base url used to load the left and right controller models
  72075. */
  72076. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  72077. /**
  72078. * The name of the left controller model file
  72079. */
  72080. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  72081. /**
  72082. * The name of the right controller model file
  72083. */
  72084. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  72085. /**
  72086. * The controller name prefix for this controller type
  72087. */
  72088. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  72089. /**
  72090. * The controller id pattern for this controller type
  72091. */
  72092. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  72093. return WindowsMotionController;
  72094. }(BABYLON.WebVRController));
  72095. BABYLON.WindowsMotionController = WindowsMotionController;
  72096. })(BABYLON || (BABYLON = {}));
  72097. //# sourceMappingURL=babylon.windowsMotionController.js.map
  72098. var BABYLON;
  72099. (function (BABYLON) {
  72100. /**
  72101. * Gear VR Controller
  72102. */
  72103. var GearVRController = /** @class */ (function (_super) {
  72104. __extends(GearVRController, _super);
  72105. /**
  72106. * Creates a new GearVRController from a gamepad
  72107. * @param vrGamepad the gamepad that the controller should be created from
  72108. */
  72109. function GearVRController(vrGamepad) {
  72110. var _this = _super.call(this, vrGamepad) || this;
  72111. _this._buttonIndexToObservableNameMap = [
  72112. 'onTrackpadChangedObservable',
  72113. 'onTriggerStateChangedObservable' // Trigger
  72114. ];
  72115. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  72116. return _this;
  72117. }
  72118. /**
  72119. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72120. * @param scene scene in which to add meshes
  72121. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72122. */
  72123. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72124. var _this = this;
  72125. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  72126. _this._defaultModel = newMeshes[1];
  72127. _this.attachToMesh(_this._defaultModel);
  72128. if (meshLoaded) {
  72129. meshLoaded(_this._defaultModel);
  72130. }
  72131. });
  72132. };
  72133. /**
  72134. * Called once for each button that changed state since the last frame
  72135. * @param buttonIdx Which button index changed
  72136. * @param state New state of the button
  72137. * @param changes Which properties on the state changed since last frame
  72138. */
  72139. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72140. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  72141. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  72142. // Only emit events for buttons that we know how to map from index to observable
  72143. var observable = this[observableName];
  72144. if (observable) {
  72145. observable.notifyObservers(state);
  72146. }
  72147. }
  72148. };
  72149. /**
  72150. * Base Url for the controller model.
  72151. */
  72152. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72153. /**
  72154. * File name for the controller model.
  72155. */
  72156. GearVRController.MODEL_FILENAME = 'generic.babylon';
  72157. /**
  72158. * Gamepad Id prefix used to identify this controller.
  72159. */
  72160. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  72161. return GearVRController;
  72162. }(BABYLON.WebVRController));
  72163. BABYLON.GearVRController = GearVRController;
  72164. })(BABYLON || (BABYLON = {}));
  72165. //# sourceMappingURL=babylon.gearVRController.js.map
  72166. var BABYLON;
  72167. (function (BABYLON) {
  72168. /**
  72169. * Google Daydream controller
  72170. */
  72171. var DaydreamController = /** @class */ (function (_super) {
  72172. __extends(DaydreamController, _super);
  72173. /**
  72174. * Creates a new DaydreamController from a gamepad
  72175. * @param vrGamepad the gamepad that the controller should be created from
  72176. */
  72177. function DaydreamController(vrGamepad) {
  72178. var _this = _super.call(this, vrGamepad) || this;
  72179. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  72180. return _this;
  72181. }
  72182. /**
  72183. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72184. * @param scene scene in which to add meshes
  72185. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72186. */
  72187. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72188. var _this = this;
  72189. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  72190. _this._defaultModel = newMeshes[1];
  72191. _this.attachToMesh(_this._defaultModel);
  72192. if (meshLoaded) {
  72193. meshLoaded(_this._defaultModel);
  72194. }
  72195. });
  72196. };
  72197. /**
  72198. * Called once for each button that changed state since the last frame
  72199. * @param buttonIdx Which button index changed
  72200. * @param state New state of the button
  72201. * @param changes Which properties on the state changed since last frame
  72202. */
  72203. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72204. // Daydream controller only has 1 GamepadButton (on the trackpad).
  72205. if (buttonIdx === 0) {
  72206. var observable = this.onTriggerStateChangedObservable;
  72207. if (observable) {
  72208. observable.notifyObservers(state);
  72209. }
  72210. }
  72211. else {
  72212. // If the app or home buttons are ever made available
  72213. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  72214. }
  72215. };
  72216. /**
  72217. * Base Url for the controller model.
  72218. */
  72219. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72220. /**
  72221. * File name for the controller model.
  72222. */
  72223. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  72224. /**
  72225. * Gamepad Id prefix used to identify Daydream Controller.
  72226. */
  72227. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  72228. return DaydreamController;
  72229. }(BABYLON.WebVRController));
  72230. BABYLON.DaydreamController = DaydreamController;
  72231. })(BABYLON || (BABYLON = {}));
  72232. //# sourceMappingURL=babylon.daydreamController.js.map
  72233. var BABYLON;
  72234. (function (BABYLON) {
  72235. var FollowCamera = /** @class */ (function (_super) {
  72236. __extends(FollowCamera, _super);
  72237. function FollowCamera(name, position, scene, lockedTarget) {
  72238. if (lockedTarget === void 0) { lockedTarget = null; }
  72239. var _this = _super.call(this, name, position, scene) || this;
  72240. _this.radius = 12;
  72241. _this.rotationOffset = 0;
  72242. _this.heightOffset = 4;
  72243. _this.cameraAcceleration = 0.05;
  72244. _this.maxCameraSpeed = 20;
  72245. _this.lockedTarget = lockedTarget;
  72246. return _this;
  72247. }
  72248. FollowCamera.prototype.getRadians = function (degrees) {
  72249. return degrees * Math.PI / 180;
  72250. };
  72251. FollowCamera.prototype.follow = function (cameraTarget) {
  72252. if (!cameraTarget)
  72253. return;
  72254. var yRotation;
  72255. if (cameraTarget.rotationQuaternion) {
  72256. var rotMatrix = new BABYLON.Matrix();
  72257. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  72258. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  72259. }
  72260. else {
  72261. yRotation = cameraTarget.rotation.y;
  72262. }
  72263. var radians = this.getRadians(this.rotationOffset) + yRotation;
  72264. var targetPosition = cameraTarget.getAbsolutePosition();
  72265. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  72266. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  72267. var dx = targetX - this.position.x;
  72268. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  72269. var dz = (targetZ) - this.position.z;
  72270. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  72271. var vy = dy * this.cameraAcceleration;
  72272. var vz = dz * this.cameraAcceleration * 2;
  72273. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  72274. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72275. }
  72276. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  72277. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72278. }
  72279. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  72280. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72281. }
  72282. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  72283. this.setTarget(targetPosition);
  72284. };
  72285. FollowCamera.prototype._checkInputs = function () {
  72286. _super.prototype._checkInputs.call(this);
  72287. if (this.lockedTarget) {
  72288. this.follow(this.lockedTarget);
  72289. }
  72290. };
  72291. FollowCamera.prototype.getClassName = function () {
  72292. return "FollowCamera";
  72293. };
  72294. __decorate([
  72295. BABYLON.serialize()
  72296. ], FollowCamera.prototype, "radius", void 0);
  72297. __decorate([
  72298. BABYLON.serialize()
  72299. ], FollowCamera.prototype, "rotationOffset", void 0);
  72300. __decorate([
  72301. BABYLON.serialize()
  72302. ], FollowCamera.prototype, "heightOffset", void 0);
  72303. __decorate([
  72304. BABYLON.serialize()
  72305. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  72306. __decorate([
  72307. BABYLON.serialize()
  72308. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  72309. __decorate([
  72310. BABYLON.serializeAsMeshReference("lockedTargetId")
  72311. ], FollowCamera.prototype, "lockedTarget", void 0);
  72312. return FollowCamera;
  72313. }(BABYLON.TargetCamera));
  72314. BABYLON.FollowCamera = FollowCamera;
  72315. var ArcFollowCamera = /** @class */ (function (_super) {
  72316. __extends(ArcFollowCamera, _super);
  72317. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  72318. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  72319. _this.alpha = alpha;
  72320. _this.beta = beta;
  72321. _this.radius = radius;
  72322. _this.target = target;
  72323. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  72324. _this.follow();
  72325. return _this;
  72326. }
  72327. ArcFollowCamera.prototype.follow = function () {
  72328. if (!this.target) {
  72329. return;
  72330. }
  72331. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  72332. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  72333. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  72334. var targetPosition = this.target.getAbsolutePosition();
  72335. this.position = targetPosition.add(this._cartesianCoordinates);
  72336. this.setTarget(targetPosition);
  72337. };
  72338. ArcFollowCamera.prototype._checkInputs = function () {
  72339. _super.prototype._checkInputs.call(this);
  72340. this.follow();
  72341. };
  72342. ArcFollowCamera.prototype.getClassName = function () {
  72343. return "ArcFollowCamera";
  72344. };
  72345. return ArcFollowCamera;
  72346. }(BABYLON.TargetCamera));
  72347. BABYLON.ArcFollowCamera = ArcFollowCamera;
  72348. })(BABYLON || (BABYLON = {}));
  72349. //# sourceMappingURL=babylon.followCamera.js.map
  72350. var BABYLON;
  72351. (function (BABYLON) {
  72352. // We're mainly based on the logic defined into the FreeCamera code
  72353. var UniversalCamera = /** @class */ (function (_super) {
  72354. __extends(UniversalCamera, _super);
  72355. //-- end properties for backward compatibility for inputs
  72356. function UniversalCamera(name, position, scene) {
  72357. var _this = _super.call(this, name, position, scene) || this;
  72358. _this.inputs.addGamepad();
  72359. return _this;
  72360. }
  72361. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  72362. //-- Begin properties for backward compatibility for inputs
  72363. get: function () {
  72364. var gamepad = this.inputs.attached["gamepad"];
  72365. if (gamepad)
  72366. return gamepad.gamepadAngularSensibility;
  72367. return 0;
  72368. },
  72369. set: function (value) {
  72370. var gamepad = this.inputs.attached["gamepad"];
  72371. if (gamepad)
  72372. gamepad.gamepadAngularSensibility = value;
  72373. },
  72374. enumerable: true,
  72375. configurable: true
  72376. });
  72377. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  72378. get: function () {
  72379. var gamepad = this.inputs.attached["gamepad"];
  72380. if (gamepad)
  72381. return gamepad.gamepadMoveSensibility;
  72382. return 0;
  72383. },
  72384. set: function (value) {
  72385. var gamepad = this.inputs.attached["gamepad"];
  72386. if (gamepad)
  72387. gamepad.gamepadMoveSensibility = value;
  72388. },
  72389. enumerable: true,
  72390. configurable: true
  72391. });
  72392. UniversalCamera.prototype.getClassName = function () {
  72393. return "UniversalCamera";
  72394. };
  72395. return UniversalCamera;
  72396. }(BABYLON.TouchCamera));
  72397. BABYLON.UniversalCamera = UniversalCamera;
  72398. })(BABYLON || (BABYLON = {}));
  72399. //# sourceMappingURL=babylon.universalCamera.js.map
  72400. var BABYLON;
  72401. (function (BABYLON) {
  72402. // We're mainly based on the logic defined into the FreeCamera code
  72403. var GamepadCamera = /** @class */ (function (_super) {
  72404. __extends(GamepadCamera, _super);
  72405. //-- end properties for backward compatibility for inputs
  72406. function GamepadCamera(name, position, scene) {
  72407. return _super.call(this, name, position, scene) || this;
  72408. }
  72409. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  72410. //-- Begin properties for backward compatibility for inputs
  72411. get: function () {
  72412. var gamepad = this.inputs.attached["gamepad"];
  72413. if (gamepad)
  72414. return gamepad.gamepadAngularSensibility;
  72415. return 0;
  72416. },
  72417. set: function (value) {
  72418. var gamepad = this.inputs.attached["gamepad"];
  72419. if (gamepad)
  72420. gamepad.gamepadAngularSensibility = value;
  72421. },
  72422. enumerable: true,
  72423. configurable: true
  72424. });
  72425. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  72426. get: function () {
  72427. var gamepad = this.inputs.attached["gamepad"];
  72428. if (gamepad)
  72429. return gamepad.gamepadMoveSensibility;
  72430. return 0;
  72431. },
  72432. set: function (value) {
  72433. var gamepad = this.inputs.attached["gamepad"];
  72434. if (gamepad)
  72435. gamepad.gamepadMoveSensibility = value;
  72436. },
  72437. enumerable: true,
  72438. configurable: true
  72439. });
  72440. GamepadCamera.prototype.getClassName = function () {
  72441. return "GamepadCamera";
  72442. };
  72443. return GamepadCamera;
  72444. }(BABYLON.UniversalCamera));
  72445. BABYLON.GamepadCamera = GamepadCamera;
  72446. })(BABYLON || (BABYLON = {}));
  72447. //# sourceMappingURL=babylon.gamepadCamera.js.map
  72448. var BABYLON;
  72449. (function (BABYLON) {
  72450. var PostProcessRenderPipelineManager = /** @class */ (function () {
  72451. function PostProcessRenderPipelineManager() {
  72452. this._renderPipelines = {};
  72453. }
  72454. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  72455. this._renderPipelines[renderPipeline._name] = renderPipeline;
  72456. };
  72457. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  72458. if (unique === void 0) { unique = false; }
  72459. var renderPipeline = this._renderPipelines[renderPipelineName];
  72460. if (!renderPipeline) {
  72461. return;
  72462. }
  72463. renderPipeline._attachCameras(cameras, unique);
  72464. };
  72465. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  72466. var renderPipeline = this._renderPipelines[renderPipelineName];
  72467. if (!renderPipeline) {
  72468. return;
  72469. }
  72470. renderPipeline._detachCameras(cameras);
  72471. };
  72472. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  72473. var renderPipeline = this._renderPipelines[renderPipelineName];
  72474. if (!renderPipeline) {
  72475. return;
  72476. }
  72477. renderPipeline._enableEffect(renderEffectName, cameras);
  72478. };
  72479. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  72480. var renderPipeline = this._renderPipelines[renderPipelineName];
  72481. if (!renderPipeline) {
  72482. return;
  72483. }
  72484. renderPipeline._disableEffect(renderEffectName, cameras);
  72485. };
  72486. PostProcessRenderPipelineManager.prototype.update = function () {
  72487. for (var renderPipelineName in this._renderPipelines) {
  72488. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72489. var pipeline = this._renderPipelines[renderPipelineName];
  72490. if (!pipeline.isSupported) {
  72491. pipeline.dispose();
  72492. delete this._renderPipelines[renderPipelineName];
  72493. }
  72494. else {
  72495. pipeline._update();
  72496. }
  72497. }
  72498. }
  72499. };
  72500. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  72501. for (var renderPipelineName in this._renderPipelines) {
  72502. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72503. var pipeline = this._renderPipelines[renderPipelineName];
  72504. pipeline._rebuild();
  72505. }
  72506. }
  72507. };
  72508. PostProcessRenderPipelineManager.prototype.dispose = function () {
  72509. for (var renderPipelineName in this._renderPipelines) {
  72510. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72511. var pipeline = this._renderPipelines[renderPipelineName];
  72512. pipeline.dispose();
  72513. }
  72514. }
  72515. };
  72516. return PostProcessRenderPipelineManager;
  72517. }());
  72518. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  72519. })(BABYLON || (BABYLON = {}));
  72520. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  72521. var BABYLON;
  72522. (function (BABYLON) {
  72523. /**
  72524. * This represents a set of one or more post processes in Babylon.
  72525. * A post process can be used to apply a shader to a texture after it is rendered.
  72526. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  72527. */
  72528. var PostProcessRenderEffect = /** @class */ (function () {
  72529. /**
  72530. * Instantiates a post process render effect.
  72531. * A post process can be used to apply a shader to a texture after it is rendered.
  72532. * @param engine The engine the effect is tied to
  72533. * @param name The name of the effect
  72534. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  72535. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  72536. */
  72537. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  72538. this._name = name;
  72539. this._singleInstance = singleInstance || true;
  72540. this._getPostProcesses = getPostProcesses;
  72541. this._cameras = {};
  72542. this._indicesForCamera = {};
  72543. this._postProcesses = {};
  72544. }
  72545. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  72546. /**
  72547. * Checks if all the post processes in the effect are supported.
  72548. */
  72549. get: function () {
  72550. for (var index in this._postProcesses) {
  72551. if (this._postProcesses.hasOwnProperty(index)) {
  72552. var pps = this._postProcesses[index];
  72553. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  72554. if (!pps[ppIndex].isSupported) {
  72555. return false;
  72556. }
  72557. }
  72558. }
  72559. }
  72560. return true;
  72561. },
  72562. enumerable: true,
  72563. configurable: true
  72564. });
  72565. /**
  72566. * Updates the current state of the effect
  72567. */
  72568. PostProcessRenderEffect.prototype._update = function () {
  72569. };
  72570. /**
  72571. * Attaches the effect on cameras
  72572. * @param cameras The camera to attach to.
  72573. */
  72574. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  72575. var _this = this;
  72576. var cameraKey;
  72577. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72578. if (!cams) {
  72579. return;
  72580. }
  72581. for (var i = 0; i < cams.length; i++) {
  72582. var camera = cams[i];
  72583. var cameraName = camera.name;
  72584. if (this._singleInstance) {
  72585. cameraKey = 0;
  72586. }
  72587. else {
  72588. cameraKey = cameraName;
  72589. }
  72590. if (!this._postProcesses[cameraKey]) {
  72591. var postProcess = this._getPostProcesses();
  72592. if (postProcess) {
  72593. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  72594. }
  72595. }
  72596. if (!this._indicesForCamera[cameraName]) {
  72597. this._indicesForCamera[cameraName] = [];
  72598. }
  72599. this._postProcesses[cameraKey].forEach(function (postProcess) {
  72600. var index = camera.attachPostProcess(postProcess);
  72601. _this._indicesForCamera[cameraName].push(index);
  72602. });
  72603. if (!this._cameras[cameraName]) {
  72604. this._cameras[cameraName] = camera;
  72605. }
  72606. }
  72607. };
  72608. /**
  72609. * Detatches the effect on cameras
  72610. * @param cameras The camera to detatch from.
  72611. */
  72612. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  72613. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72614. if (!cams) {
  72615. return;
  72616. }
  72617. for (var i = 0; i < cams.length; i++) {
  72618. var camera = cams[i];
  72619. var cameraName = camera.name;
  72620. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  72621. camera.detachPostProcess(postProcess);
  72622. });
  72623. if (this._cameras[cameraName]) {
  72624. //this._indicesForCamera.splice(index, 1);
  72625. this._cameras[cameraName] = null;
  72626. }
  72627. }
  72628. };
  72629. /**
  72630. * Enables the effect on given cameras
  72631. * @param cameras The camera to enable.
  72632. */
  72633. PostProcessRenderEffect.prototype._enable = function (cameras) {
  72634. var _this = this;
  72635. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72636. if (!cams) {
  72637. return;
  72638. }
  72639. for (var i = 0; i < cams.length; i++) {
  72640. var camera = cams[i];
  72641. var cameraName = camera.name;
  72642. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  72643. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  72644. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  72645. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  72646. });
  72647. }
  72648. }
  72649. }
  72650. };
  72651. /**
  72652. * Disables the effect on the given cameras
  72653. * @param cameras The camera to disable.
  72654. */
  72655. PostProcessRenderEffect.prototype._disable = function (cameras) {
  72656. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72657. if (!cams) {
  72658. return;
  72659. }
  72660. for (var i = 0; i < cams.length; i++) {
  72661. var camera = cams[i];
  72662. var cameraName = camera.name;
  72663. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  72664. camera.detachPostProcess(postProcess);
  72665. });
  72666. }
  72667. };
  72668. /**
  72669. * Gets a list of the post processes contained in the effect.
  72670. * @param camera The camera to get the post processes on.
  72671. * @returns The list of the post processes in the effect.
  72672. */
  72673. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  72674. if (this._singleInstance) {
  72675. return this._postProcesses[0];
  72676. }
  72677. else {
  72678. if (!camera) {
  72679. return null;
  72680. }
  72681. return this._postProcesses[camera.name];
  72682. }
  72683. };
  72684. return PostProcessRenderEffect;
  72685. }());
  72686. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  72687. })(BABYLON || (BABYLON = {}));
  72688. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  72689. var BABYLON;
  72690. (function (BABYLON) {
  72691. var PostProcessRenderPipeline = /** @class */ (function () {
  72692. function PostProcessRenderPipeline(engine, name) {
  72693. this.engine = engine;
  72694. this._name = name;
  72695. this._renderEffects = {};
  72696. this._renderEffectsForIsolatedPass = new Array();
  72697. this._cameras = [];
  72698. }
  72699. PostProcessRenderPipeline.prototype.getClassName = function () {
  72700. return "PostProcessRenderPipeline";
  72701. };
  72702. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  72703. get: function () {
  72704. for (var renderEffectName in this._renderEffects) {
  72705. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72706. if (!this._renderEffects[renderEffectName].isSupported) {
  72707. return false;
  72708. }
  72709. }
  72710. }
  72711. return true;
  72712. },
  72713. enumerable: true,
  72714. configurable: true
  72715. });
  72716. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  72717. this._renderEffects[renderEffect._name] = renderEffect;
  72718. };
  72719. // private
  72720. PostProcessRenderPipeline.prototype._rebuild = function () {
  72721. };
  72722. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  72723. var renderEffects = this._renderEffects[renderEffectName];
  72724. if (!renderEffects) {
  72725. return;
  72726. }
  72727. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  72728. };
  72729. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  72730. var renderEffects = this._renderEffects[renderEffectName];
  72731. if (!renderEffects) {
  72732. return;
  72733. }
  72734. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  72735. };
  72736. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  72737. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72738. if (!cams) {
  72739. return;
  72740. }
  72741. var indicesToDelete = [];
  72742. var i;
  72743. for (i = 0; i < cams.length; i++) {
  72744. var camera = cams[i];
  72745. var cameraName = camera.name;
  72746. if (this._cameras.indexOf(camera) === -1) {
  72747. this._cameras[cameraName] = camera;
  72748. }
  72749. else if (unique) {
  72750. indicesToDelete.push(i);
  72751. }
  72752. }
  72753. for (i = 0; i < indicesToDelete.length; i++) {
  72754. cameras.splice(indicesToDelete[i], 1);
  72755. }
  72756. for (var renderEffectName in this._renderEffects) {
  72757. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72758. this._renderEffects[renderEffectName]._attachCameras(cams);
  72759. }
  72760. }
  72761. };
  72762. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  72763. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72764. if (!cams) {
  72765. return;
  72766. }
  72767. for (var renderEffectName in this._renderEffects) {
  72768. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72769. this._renderEffects[renderEffectName]._detachCameras(cams);
  72770. }
  72771. }
  72772. for (var i = 0; i < cams.length; i++) {
  72773. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  72774. }
  72775. };
  72776. PostProcessRenderPipeline.prototype._update = function () {
  72777. for (var renderEffectName in this._renderEffects) {
  72778. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72779. this._renderEffects[renderEffectName]._update();
  72780. }
  72781. }
  72782. for (var i = 0; i < this._cameras.length; i++) {
  72783. var cameraName = this._cameras[i].name;
  72784. if (this._renderEffectsForIsolatedPass[cameraName]) {
  72785. this._renderEffectsForIsolatedPass[cameraName]._update();
  72786. }
  72787. }
  72788. };
  72789. PostProcessRenderPipeline.prototype._reset = function () {
  72790. this._renderEffects = {};
  72791. this._renderEffectsForIsolatedPass = new Array();
  72792. };
  72793. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  72794. // 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)
  72795. var effectKeys = Object.keys(this._renderEffects);
  72796. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  72797. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  72798. if (postProcesses) {
  72799. postProcesses[0].samples = sampleCount;
  72800. return true;
  72801. }
  72802. }
  72803. return false;
  72804. };
  72805. PostProcessRenderPipeline.prototype.dispose = function () {
  72806. // Must be implemented by children
  72807. };
  72808. __decorate([
  72809. BABYLON.serialize()
  72810. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  72811. return PostProcessRenderPipeline;
  72812. }());
  72813. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  72814. })(BABYLON || (BABYLON = {}));
  72815. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  72816. var BABYLON;
  72817. (function (BABYLON) {
  72818. /**
  72819. * This represents a depth renderer in Babylon.
  72820. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  72821. */
  72822. var DepthRenderer = /** @class */ (function () {
  72823. /**
  72824. * Instantiates a depth renderer
  72825. * @param scene The scene the renderer belongs to
  72826. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  72827. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  72828. */
  72829. function DepthRenderer(scene, type, camera) {
  72830. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  72831. if (camera === void 0) { camera = null; }
  72832. var _this = this;
  72833. this._scene = scene;
  72834. this._camera = camera;
  72835. var engine = scene.getEngine();
  72836. // Render target
  72837. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  72838. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72839. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72840. this._depthMap.refreshRate = 1;
  72841. this._depthMap.renderParticles = false;
  72842. this._depthMap.renderList = null;
  72843. // Camera to get depth map from to support multiple concurrent cameras
  72844. this._depthMap.activeCamera = this._camera;
  72845. this._depthMap.ignoreCameraViewport = true;
  72846. this._depthMap.useCameraPostProcesses = false;
  72847. // set default depth value to 1.0 (far away)
  72848. this._depthMap.onClearObservable.add(function (engine) {
  72849. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  72850. });
  72851. // Custom render function
  72852. var renderSubMesh = function (subMesh) {
  72853. var mesh = subMesh.getRenderingMesh();
  72854. var scene = _this._scene;
  72855. var engine = scene.getEngine();
  72856. var material = subMesh.getMaterial();
  72857. if (!material) {
  72858. return;
  72859. }
  72860. // Culling and reverse (right handed system)
  72861. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  72862. // Managing instances
  72863. var batch = mesh._getInstancesRenderList(subMesh._id);
  72864. if (batch.mustReturn) {
  72865. return;
  72866. }
  72867. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  72868. var camera = _this._camera || scene.activeCamera;
  72869. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  72870. engine.enableEffect(_this._effect);
  72871. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  72872. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  72873. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  72874. // Alpha test
  72875. if (material && material.needAlphaTesting()) {
  72876. var alphaTexture = material.getAlphaTestTexture();
  72877. if (alphaTexture) {
  72878. _this._effect.setTexture("diffuseSampler", alphaTexture);
  72879. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  72880. }
  72881. }
  72882. // Bones
  72883. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  72884. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  72885. }
  72886. // Draw
  72887. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  72888. }
  72889. };
  72890. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  72891. var index;
  72892. if (depthOnlySubMeshes.length) {
  72893. engine.setColorWrite(false);
  72894. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  72895. renderSubMesh(depthOnlySubMeshes.data[index]);
  72896. }
  72897. engine.setColorWrite(true);
  72898. }
  72899. for (index = 0; index < opaqueSubMeshes.length; index++) {
  72900. renderSubMesh(opaqueSubMeshes.data[index]);
  72901. }
  72902. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  72903. renderSubMesh(alphaTestSubMeshes.data[index]);
  72904. }
  72905. };
  72906. }
  72907. /**
  72908. * Creates the depth rendering effect and checks if the effect is ready.
  72909. * @param subMesh The submesh to be used to render the depth map of
  72910. * @param useInstances If multiple world instances should be used
  72911. * @returns if the depth renderer is ready to render the depth map
  72912. */
  72913. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  72914. var material = subMesh.getMaterial();
  72915. if (material.disableDepthWrite) {
  72916. return false;
  72917. }
  72918. var defines = [];
  72919. var attribs = [BABYLON.VertexBuffer.PositionKind];
  72920. var mesh = subMesh.getMesh();
  72921. // Alpha test
  72922. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  72923. defines.push("#define ALPHATEST");
  72924. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  72925. attribs.push(BABYLON.VertexBuffer.UVKind);
  72926. defines.push("#define UV1");
  72927. }
  72928. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  72929. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  72930. defines.push("#define UV2");
  72931. }
  72932. }
  72933. // Bones
  72934. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  72935. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  72936. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  72937. if (mesh.numBoneInfluencers > 4) {
  72938. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  72939. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  72940. }
  72941. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  72942. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  72943. }
  72944. else {
  72945. defines.push("#define NUM_BONE_INFLUENCERS 0");
  72946. }
  72947. // Instances
  72948. if (useInstances) {
  72949. defines.push("#define INSTANCES");
  72950. attribs.push("world0");
  72951. attribs.push("world1");
  72952. attribs.push("world2");
  72953. attribs.push("world3");
  72954. }
  72955. // Get correct effect
  72956. var join = defines.join("\n");
  72957. if (this._cachedDefines !== join) {
  72958. this._cachedDefines = join;
  72959. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  72960. }
  72961. return this._effect.isReady();
  72962. };
  72963. /**
  72964. * Gets the texture which the depth map will be written to.
  72965. * @returns The depth map texture
  72966. */
  72967. DepthRenderer.prototype.getDepthMap = function () {
  72968. return this._depthMap;
  72969. };
  72970. /**
  72971. * Disposes of the depth renderer.
  72972. */
  72973. DepthRenderer.prototype.dispose = function () {
  72974. this._depthMap.dispose();
  72975. };
  72976. return DepthRenderer;
  72977. }());
  72978. BABYLON.DepthRenderer = DepthRenderer;
  72979. })(BABYLON || (BABYLON = {}));
  72980. //# sourceMappingURL=babylon.depthRenderer.js.map
  72981. var BABYLON;
  72982. (function (BABYLON) {
  72983. var SSAORenderingPipeline = /** @class */ (function (_super) {
  72984. __extends(SSAORenderingPipeline, _super);
  72985. /**
  72986. * @constructor
  72987. * @param {string} name - The rendering pipeline name
  72988. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  72989. * @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 }
  72990. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  72991. */
  72992. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  72993. var _this = _super.call(this, scene.getEngine(), name) || this;
  72994. // Members
  72995. /**
  72996. * The PassPostProcess id in the pipeline that contains the original scene color
  72997. */
  72998. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  72999. /**
  73000. * The SSAO PostProcess id in the pipeline
  73001. */
  73002. _this.SSAORenderEffect = "SSAORenderEffect";
  73003. /**
  73004. * The horizontal blur PostProcess id in the pipeline
  73005. */
  73006. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  73007. /**
  73008. * The vertical blur PostProcess id in the pipeline
  73009. */
  73010. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  73011. /**
  73012. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  73013. */
  73014. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  73015. /**
  73016. * The output strength of the SSAO post-process. Default value is 1.0.
  73017. */
  73018. _this.totalStrength = 1.0;
  73019. /**
  73020. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  73021. */
  73022. _this.radius = 0.0001;
  73023. /**
  73024. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  73025. * Must not be equal to fallOff and superior to fallOff.
  73026. * Default value is 0.975
  73027. */
  73028. _this.area = 0.0075;
  73029. /**
  73030. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  73031. * Must not be equal to area and inferior to area.
  73032. * Default value is 0.0
  73033. */
  73034. _this.fallOff = 0.000001;
  73035. /**
  73036. * The base color of the SSAO post-process
  73037. * The final result is "base + ssao" between [0, 1]
  73038. */
  73039. _this.base = 0.5;
  73040. _this._firstUpdate = true;
  73041. _this._scene = scene;
  73042. // Set up assets
  73043. _this._createRandomTexture();
  73044. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  73045. var ssaoRatio = ratio.ssaoRatio || ratio;
  73046. var combineRatio = ratio.combineRatio || ratio;
  73047. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  73048. _this._createSSAOPostProcess(ssaoRatio);
  73049. _this._createBlurPostProcess(ssaoRatio);
  73050. _this._createSSAOCombinePostProcess(combineRatio);
  73051. // Set up pipeline
  73052. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  73053. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  73054. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  73055. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  73056. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  73057. // Finish
  73058. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73059. if (cameras)
  73060. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73061. return _this;
  73062. }
  73063. // Public Methods
  73064. /**
  73065. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  73066. */
  73067. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  73068. if (disableDepthRender === void 0) { disableDepthRender = false; }
  73069. for (var i = 0; i < this._scene.cameras.length; i++) {
  73070. var camera = this._scene.cameras[i];
  73071. this._originalColorPostProcess.dispose(camera);
  73072. this._ssaoPostProcess.dispose(camera);
  73073. this._blurHPostProcess.dispose(camera);
  73074. this._blurVPostProcess.dispose(camera);
  73075. this._ssaoCombinePostProcess.dispose(camera);
  73076. }
  73077. this._randomTexture.dispose();
  73078. if (disableDepthRender)
  73079. this._scene.disableDepthRenderer();
  73080. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73081. _super.prototype.dispose.call(this);
  73082. };
  73083. // Private Methods
  73084. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  73085. var _this = this;
  73086. var size = 16;
  73087. 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);
  73088. 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);
  73089. this._blurHPostProcess.onActivateObservable.add(function () {
  73090. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  73091. _this._blurHPostProcess.kernel = size * dw;
  73092. });
  73093. this._blurVPostProcess.onActivateObservable.add(function () {
  73094. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  73095. _this._blurVPostProcess.kernel = size * dw;
  73096. });
  73097. };
  73098. SSAORenderingPipeline.prototype._rebuild = function () {
  73099. this._firstUpdate = true;
  73100. _super.prototype._rebuild.call(this);
  73101. };
  73102. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  73103. var _this = this;
  73104. var numSamples = 16;
  73105. var sampleSphere = [
  73106. 0.5381, 0.1856, -0.4319,
  73107. 0.1379, 0.2486, 0.4430,
  73108. 0.3371, 0.5679, -0.0057,
  73109. -0.6999, -0.0451, -0.0019,
  73110. 0.0689, -0.1598, -0.8547,
  73111. 0.0560, 0.0069, -0.1843,
  73112. -0.0146, 0.1402, 0.0762,
  73113. 0.0100, -0.1924, -0.0344,
  73114. -0.3577, -0.5301, -0.4358,
  73115. -0.3169, 0.1063, 0.0158,
  73116. 0.0103, -0.5869, 0.0046,
  73117. -0.0897, -0.4940, 0.3287,
  73118. 0.7119, -0.0154, -0.0918,
  73119. -0.0533, 0.0596, -0.5411,
  73120. 0.0352, -0.0631, 0.5460,
  73121. -0.4776, 0.2847, -0.0271
  73122. ];
  73123. var samplesFactor = 1.0 / numSamples;
  73124. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  73125. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  73126. "area", "fallOff", "base", "range", "viewport"
  73127. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  73128. this._ssaoPostProcess.onApply = function (effect) {
  73129. if (_this._firstUpdate) {
  73130. effect.setArray3("sampleSphere", sampleSphere);
  73131. effect.setFloat("samplesFactor", samplesFactor);
  73132. effect.setFloat("randTextureTiles", 4.0);
  73133. }
  73134. effect.setFloat("totalStrength", _this.totalStrength);
  73135. effect.setFloat("radius", _this.radius);
  73136. effect.setFloat("area", _this.area);
  73137. effect.setFloat("fallOff", _this.fallOff);
  73138. effect.setFloat("base", _this.base);
  73139. effect.setTexture("textureSampler", _this._depthTexture);
  73140. effect.setTexture("randomSampler", _this._randomTexture);
  73141. };
  73142. };
  73143. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  73144. var _this = this;
  73145. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73146. this._ssaoCombinePostProcess.onApply = function (effect) {
  73147. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  73148. };
  73149. };
  73150. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  73151. var size = 512;
  73152. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  73153. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73154. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73155. var context = this._randomTexture.getContext();
  73156. var rand = function (min, max) {
  73157. return Math.random() * (max - min) + min;
  73158. };
  73159. var randVector = BABYLON.Vector3.Zero();
  73160. for (var x = 0; x < size; x++) {
  73161. for (var y = 0; y < size; y++) {
  73162. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  73163. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  73164. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  73165. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  73166. context.fillRect(x, y, 1, 1);
  73167. }
  73168. }
  73169. this._randomTexture.update(false);
  73170. };
  73171. __decorate([
  73172. BABYLON.serialize()
  73173. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  73174. __decorate([
  73175. BABYLON.serialize()
  73176. ], SSAORenderingPipeline.prototype, "radius", void 0);
  73177. __decorate([
  73178. BABYLON.serialize()
  73179. ], SSAORenderingPipeline.prototype, "area", void 0);
  73180. __decorate([
  73181. BABYLON.serialize()
  73182. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  73183. __decorate([
  73184. BABYLON.serialize()
  73185. ], SSAORenderingPipeline.prototype, "base", void 0);
  73186. return SSAORenderingPipeline;
  73187. }(BABYLON.PostProcessRenderPipeline));
  73188. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  73189. })(BABYLON || (BABYLON = {}));
  73190. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  73191. var BABYLON;
  73192. (function (BABYLON) {
  73193. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  73194. __extends(SSAO2RenderingPipeline, _super);
  73195. /**
  73196. * @constructor
  73197. * @param {string} name - The rendering pipeline name
  73198. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73199. * @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 }
  73200. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73201. */
  73202. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  73203. var _this = _super.call(this, scene.getEngine(), name) || this;
  73204. // Members
  73205. /**
  73206. * The PassPostProcess id in the pipeline that contains the original scene color
  73207. */
  73208. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  73209. /**
  73210. * The SSAO PostProcess id in the pipeline
  73211. */
  73212. _this.SSAORenderEffect = "SSAORenderEffect";
  73213. /**
  73214. * The horizontal blur PostProcess id in the pipeline
  73215. */
  73216. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  73217. /**
  73218. * The vertical blur PostProcess id in the pipeline
  73219. */
  73220. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  73221. /**
  73222. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  73223. */
  73224. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  73225. /**
  73226. * The output strength of the SSAO post-process. Default value is 1.0.
  73227. */
  73228. _this.totalStrength = 1.0;
  73229. /**
  73230. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  73231. */
  73232. _this.maxZ = 100.0;
  73233. /**
  73234. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  73235. */
  73236. _this.minZAspect = 0.2;
  73237. /**
  73238. * Number of samples used for the SSAO calculations. Default value is 8
  73239. */
  73240. _this._samples = 8;
  73241. /**
  73242. * Are we using bilateral blur ?
  73243. */
  73244. _this._expensiveBlur = true;
  73245. /**
  73246. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  73247. */
  73248. _this.radius = 2.0;
  73249. /**
  73250. * The base color of the SSAO post-process
  73251. * The final result is "base + ssao" between [0, 1]
  73252. */
  73253. _this.base = 0.1;
  73254. _this._firstUpdate = true;
  73255. _this._scene = scene;
  73256. _this._ratio = ratio;
  73257. if (!_this.isSupported) {
  73258. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  73259. return _this;
  73260. }
  73261. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  73262. var blurRatio = _this._ratio.blurRatio || ratio;
  73263. // Set up assets
  73264. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  73265. _this._createRandomTexture();
  73266. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  73267. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  73268. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  73269. _this._createSSAOPostProcess(1.0);
  73270. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  73271. _this._createSSAOCombinePostProcess(blurRatio);
  73272. // Set up pipeline
  73273. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  73274. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  73275. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  73276. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  73277. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  73278. // Finish
  73279. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73280. if (cameras)
  73281. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73282. return _this;
  73283. }
  73284. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  73285. get: function () {
  73286. return this._samples;
  73287. },
  73288. set: function (n) {
  73289. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  73290. this._samples = n;
  73291. this._sampleSphere = this._generateHemisphere();
  73292. this._firstUpdate = true;
  73293. },
  73294. enumerable: true,
  73295. configurable: true
  73296. });
  73297. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  73298. get: function () {
  73299. return this._expensiveBlur;
  73300. },
  73301. set: function (b) {
  73302. 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"]);
  73303. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  73304. this._expensiveBlur = b;
  73305. this._firstUpdate = true;
  73306. },
  73307. enumerable: true,
  73308. configurable: true
  73309. });
  73310. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  73311. /**
  73312. * Support test.
  73313. */
  73314. get: function () {
  73315. var engine = BABYLON.Engine.LastCreatedEngine;
  73316. if (!engine) {
  73317. return false;
  73318. }
  73319. return engine.getCaps().drawBuffersExtension;
  73320. },
  73321. enumerable: true,
  73322. configurable: true
  73323. });
  73324. // Public Methods
  73325. /**
  73326. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  73327. */
  73328. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  73329. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  73330. for (var i = 0; i < this._scene.cameras.length; i++) {
  73331. var camera = this._scene.cameras[i];
  73332. this._originalColorPostProcess.dispose(camera);
  73333. this._ssaoPostProcess.dispose(camera);
  73334. this._blurHPostProcess.dispose(camera);
  73335. this._blurVPostProcess.dispose(camera);
  73336. this._ssaoCombinePostProcess.dispose(camera);
  73337. }
  73338. this._randomTexture.dispose();
  73339. if (disableGeometryBufferRenderer)
  73340. this._scene.disableGeometryBufferRenderer();
  73341. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73342. _super.prototype.dispose.call(this);
  73343. };
  73344. // Private Methods
  73345. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  73346. var _this = this;
  73347. this._samplerOffsets = [];
  73348. var expensive = this.expensiveBlur;
  73349. for (var i = -8; i < 8; i++) {
  73350. this._samplerOffsets.push(i * 2 + 0.5);
  73351. }
  73352. 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");
  73353. this._blurHPostProcess.onApply = function (effect) {
  73354. if (!_this._scene.activeCamera) {
  73355. return;
  73356. }
  73357. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  73358. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73359. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73360. effect.setFloat("radius", _this.radius);
  73361. effect.setTexture("depthSampler", _this._depthTexture);
  73362. if (_this._firstUpdate) {
  73363. effect.setArray("samplerOffsets", _this._samplerOffsets);
  73364. }
  73365. };
  73366. 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");
  73367. this._blurVPostProcess.onApply = function (effect) {
  73368. if (!_this._scene.activeCamera) {
  73369. return;
  73370. }
  73371. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  73372. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73373. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73374. effect.setFloat("radius", _this.radius);
  73375. effect.setTexture("depthSampler", _this._depthTexture);
  73376. if (_this._firstUpdate) {
  73377. effect.setArray("samplerOffsets", _this._samplerOffsets);
  73378. _this._firstUpdate = false;
  73379. }
  73380. };
  73381. };
  73382. SSAO2RenderingPipeline.prototype._rebuild = function () {
  73383. this._firstUpdate = true;
  73384. _super.prototype._rebuild.call(this);
  73385. };
  73386. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  73387. var numSamples = this.samples;
  73388. var result = [];
  73389. var vector, scale;
  73390. var rand = function (min, max) {
  73391. return Math.random() * (max - min) + min;
  73392. };
  73393. var i = 0;
  73394. while (i < numSamples) {
  73395. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  73396. vector.normalize();
  73397. scale = i / numSamples;
  73398. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  73399. vector.scaleInPlace(scale);
  73400. result.push(vector.x, vector.y, vector.z);
  73401. i++;
  73402. }
  73403. return result;
  73404. };
  73405. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  73406. var _this = this;
  73407. var numSamples = this.samples;
  73408. this._sampleSphere = this._generateHemisphere();
  73409. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  73410. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  73411. "base", "range", "projection", "near", "far", "texelSize",
  73412. "xViewport", "yViewport", "maxZ", "minZAspect"
  73413. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  73414. this._ssaoPostProcess.onApply = function (effect) {
  73415. if (_this._firstUpdate) {
  73416. effect.setArray3("sampleSphere", _this._sampleSphere);
  73417. effect.setFloat("randTextureTiles", 4.0);
  73418. }
  73419. if (!_this._scene.activeCamera) {
  73420. return;
  73421. }
  73422. effect.setFloat("samplesFactor", 1 / _this.samples);
  73423. effect.setFloat("totalStrength", _this.totalStrength);
  73424. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  73425. effect.setFloat("radius", _this.radius);
  73426. effect.setFloat("maxZ", _this.maxZ);
  73427. effect.setFloat("minZAspect", _this.minZAspect);
  73428. effect.setFloat("base", _this.base);
  73429. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73430. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73431. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  73432. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  73433. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  73434. effect.setTexture("textureSampler", _this._depthTexture);
  73435. effect.setTexture("normalSampler", _this._normalTexture);
  73436. effect.setTexture("randomSampler", _this._randomTexture);
  73437. };
  73438. };
  73439. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  73440. var _this = this;
  73441. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73442. this._ssaoCombinePostProcess.onApply = function (effect) {
  73443. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  73444. };
  73445. };
  73446. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  73447. var size = 512;
  73448. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  73449. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73450. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73451. var context = this._randomTexture.getContext();
  73452. var rand = function (min, max) {
  73453. return Math.random() * (max - min) + min;
  73454. };
  73455. var randVector = BABYLON.Vector3.Zero();
  73456. for (var x = 0; x < size; x++) {
  73457. for (var y = 0; y < size; y++) {
  73458. randVector.x = rand(0.0, 1.0);
  73459. randVector.y = rand(0.0, 1.0);
  73460. randVector.z = 0.0;
  73461. randVector.normalize();
  73462. randVector.scaleInPlace(255);
  73463. randVector.x = Math.floor(randVector.x);
  73464. randVector.y = Math.floor(randVector.y);
  73465. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  73466. context.fillRect(x, y, 1, 1);
  73467. }
  73468. }
  73469. this._randomTexture.update(false);
  73470. };
  73471. /**
  73472. * Serialize the rendering pipeline (Used when exporting)
  73473. * @returns the serialized object
  73474. */
  73475. SSAO2RenderingPipeline.prototype.serialize = function () {
  73476. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  73477. serializationObject.customType = "SSAO2RenderingPipeline";
  73478. return serializationObject;
  73479. };
  73480. /**
  73481. * Parse the serialized pipeline
  73482. * @param source Source pipeline.
  73483. * @param scene The scene to load the pipeline to.
  73484. * @param rootUrl The URL of the serialized pipeline.
  73485. * @returns An instantiated pipeline from the serialized object.
  73486. */
  73487. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  73488. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  73489. };
  73490. __decorate([
  73491. BABYLON.serialize()
  73492. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  73493. __decorate([
  73494. BABYLON.serialize()
  73495. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  73496. __decorate([
  73497. BABYLON.serialize()
  73498. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  73499. __decorate([
  73500. BABYLON.serialize("samples")
  73501. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  73502. __decorate([
  73503. BABYLON.serialize()
  73504. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  73505. __decorate([
  73506. BABYLON.serialize("expensiveBlur")
  73507. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  73508. __decorate([
  73509. BABYLON.serialize()
  73510. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  73511. __decorate([
  73512. BABYLON.serialize()
  73513. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  73514. return SSAO2RenderingPipeline;
  73515. }(BABYLON.PostProcessRenderPipeline));
  73516. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  73517. })(BABYLON || (BABYLON = {}));
  73518. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  73519. // BABYLON.JS Chromatic Aberration GLSL Shader
  73520. // Author: Olivier Guyot
  73521. // Separates very slightly R, G and B colors on the edges of the screen
  73522. // Inspired by Francois Tarlier & Martins Upitis
  73523. var BABYLON;
  73524. (function (BABYLON) {
  73525. var LensRenderingPipeline = /** @class */ (function (_super) {
  73526. __extends(LensRenderingPipeline, _super);
  73527. /**
  73528. * @constructor
  73529. *
  73530. * Effect parameters are as follow:
  73531. * {
  73532. * chromatic_aberration: number; // from 0 to x (1 for realism)
  73533. * edge_blur: number; // from 0 to x (1 for realism)
  73534. * distortion: number; // from 0 to x (1 for realism)
  73535. * grain_amount: number; // from 0 to 1
  73536. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  73537. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  73538. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  73539. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  73540. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  73541. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  73542. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  73543. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  73544. * }
  73545. * Note: if an effect parameter is unset, effect is disabled
  73546. *
  73547. * @param {string} name - The rendering pipeline name
  73548. * @param {object} parameters - An object containing all parameters (see above)
  73549. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73550. * @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)
  73551. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73552. */
  73553. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  73554. if (ratio === void 0) { ratio = 1.0; }
  73555. var _this = _super.call(this, scene.getEngine(), name) || this;
  73556. // Lens effects can be of the following:
  73557. // - chromatic aberration (slight shift of RGB colors)
  73558. // - blur on the edge of the lens
  73559. // - lens distortion
  73560. // - depth-of-field blur & highlights enhancing
  73561. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  73562. // - grain effect (noise or custom texture)
  73563. // Two additional texture samplers are needed:
  73564. // - depth map (for depth-of-field)
  73565. // - grain texture
  73566. /**
  73567. * The chromatic aberration PostProcess id in the pipeline
  73568. */
  73569. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  73570. /**
  73571. * The highlights enhancing PostProcess id in the pipeline
  73572. */
  73573. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  73574. /**
  73575. * The depth-of-field PostProcess id in the pipeline
  73576. */
  73577. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  73578. _this._scene = scene;
  73579. // Fetch texture samplers
  73580. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  73581. if (parameters.grain_texture) {
  73582. _this._grainTexture = parameters.grain_texture;
  73583. }
  73584. else {
  73585. _this._createGrainTexture();
  73586. }
  73587. // save parameters
  73588. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  73589. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  73590. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  73591. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  73592. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  73593. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  73594. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  73595. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  73596. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  73597. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  73598. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  73599. // Create effects
  73600. _this._createChromaticAberrationPostProcess(ratio);
  73601. _this._createHighlightsPostProcess(ratio);
  73602. _this._createDepthOfFieldPostProcess(ratio / 4);
  73603. // Set up pipeline
  73604. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  73605. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  73606. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  73607. if (_this._highlightsGain === -1) {
  73608. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  73609. }
  73610. // Finish
  73611. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73612. if (cameras) {
  73613. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73614. }
  73615. return _this;
  73616. }
  73617. // public methods (self explanatory)
  73618. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  73619. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  73620. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  73621. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  73622. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  73623. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  73624. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  73625. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  73626. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  73627. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  73628. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  73629. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  73630. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  73631. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  73632. };
  73633. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  73634. this._highlightsPostProcess.updateEffect();
  73635. };
  73636. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  73637. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  73638. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  73639. this._highlightsGain = amount;
  73640. };
  73641. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  73642. if (this._highlightsGain === -1) {
  73643. this._highlightsGain = 1.0;
  73644. }
  73645. this._highlightsThreshold = amount;
  73646. };
  73647. LensRenderingPipeline.prototype.disableHighlights = function () {
  73648. this._highlightsGain = -1;
  73649. };
  73650. /**
  73651. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  73652. */
  73653. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  73654. if (disableDepthRender === void 0) { disableDepthRender = false; }
  73655. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73656. this._chromaticAberrationPostProcess = null;
  73657. this._highlightsPostProcess = null;
  73658. this._depthOfFieldPostProcess = null;
  73659. this._grainTexture.dispose();
  73660. if (disableDepthRender)
  73661. this._scene.disableDepthRenderer();
  73662. };
  73663. // colors shifting and distortion
  73664. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  73665. var _this = this;
  73666. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  73667. [], // samplers
  73668. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73669. this._chromaticAberrationPostProcess.onApply = function (effect) {
  73670. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  73671. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  73672. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  73673. effect.setFloat('radialIntensity', 1);
  73674. effect.setFloat2('direction', 17, 17);
  73675. effect.setFloat2('centerPosition', 0.5, 0.5);
  73676. };
  73677. };
  73678. // highlights enhancing
  73679. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  73680. var _this = this;
  73681. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  73682. [], // samplers
  73683. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  73684. this._highlightsPostProcess.onApply = function (effect) {
  73685. effect.setFloat('gain', _this._highlightsGain);
  73686. effect.setFloat('threshold', _this._highlightsThreshold);
  73687. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  73688. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  73689. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  73690. };
  73691. };
  73692. // colors shifting and distortion
  73693. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  73694. var _this = this;
  73695. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  73696. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  73697. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  73698. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73699. this._depthOfFieldPostProcess.onApply = function (effect) {
  73700. effect.setTexture("depthSampler", _this._depthTexture);
  73701. effect.setTexture("grainSampler", _this._grainTexture);
  73702. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  73703. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  73704. effect.setFloat('grain_amount', _this._grainAmount);
  73705. effect.setBool('blur_noise', _this._blurNoise);
  73706. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  73707. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  73708. effect.setFloat('distortion', _this._distortion);
  73709. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  73710. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  73711. effect.setFloat('aperture', _this._dofAperture);
  73712. effect.setFloat('darken', _this._dofDarken);
  73713. effect.setFloat('edge_blur', _this._edgeBlur);
  73714. effect.setBool('highlights', (_this._highlightsGain !== -1));
  73715. if (_this._scene.activeCamera) {
  73716. effect.setFloat('near', _this._scene.activeCamera.minZ);
  73717. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  73718. }
  73719. };
  73720. };
  73721. // creates a black and white random noise texture, 512x512
  73722. LensRenderingPipeline.prototype._createGrainTexture = function () {
  73723. var size = 512;
  73724. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  73725. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73726. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73727. var context = this._grainTexture.getContext();
  73728. var rand = function (min, max) {
  73729. return Math.random() * (max - min) + min;
  73730. };
  73731. var value;
  73732. for (var x = 0; x < size; x++) {
  73733. for (var y = 0; y < size; y++) {
  73734. value = Math.floor(rand(0.42, 0.58) * 255);
  73735. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  73736. context.fillRect(x, y, 1, 1);
  73737. }
  73738. }
  73739. this._grainTexture.update(false);
  73740. };
  73741. return LensRenderingPipeline;
  73742. }(BABYLON.PostProcessRenderPipeline));
  73743. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  73744. })(BABYLON || (BABYLON = {}));
  73745. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  73746. var BABYLON;
  73747. (function (BABYLON) {
  73748. var StandardRenderingPipeline = /** @class */ (function (_super) {
  73749. __extends(StandardRenderingPipeline, _super);
  73750. /**
  73751. * @constructor
  73752. * @param {string} name - The rendering pipeline name
  73753. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73754. * @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)
  73755. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  73756. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73757. */
  73758. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  73759. if (originalPostProcess === void 0) { originalPostProcess = null; }
  73760. var _this = _super.call(this, scene.getEngine(), name) || this;
  73761. _this.downSampleX4PostProcess = null;
  73762. _this.brightPassPostProcess = null;
  73763. _this.blurHPostProcesses = [];
  73764. _this.blurVPostProcesses = [];
  73765. _this.textureAdderPostProcess = null;
  73766. _this.volumetricLightPostProcess = null;
  73767. _this.volumetricLightSmoothXPostProcess = null;
  73768. _this.volumetricLightSmoothYPostProcess = null;
  73769. _this.volumetricLightMergePostProces = null;
  73770. _this.volumetricLightFinalPostProcess = null;
  73771. _this.luminancePostProcess = null;
  73772. _this.luminanceDownSamplePostProcesses = [];
  73773. _this.hdrPostProcess = null;
  73774. _this.textureAdderFinalPostProcess = null;
  73775. _this.lensFlareFinalPostProcess = null;
  73776. _this.hdrFinalPostProcess = null;
  73777. _this.lensFlarePostProcess = null;
  73778. _this.lensFlareComposePostProcess = null;
  73779. _this.motionBlurPostProcess = null;
  73780. _this.depthOfFieldPostProcess = null;
  73781. // Values
  73782. _this.brightThreshold = 1.0;
  73783. _this.blurWidth = 512.0;
  73784. _this.horizontalBlur = false;
  73785. _this.exposure = 1.0;
  73786. _this.lensTexture = null;
  73787. _this.volumetricLightCoefficient = 0.2;
  73788. _this.volumetricLightPower = 4.0;
  73789. _this.volumetricLightBlurScale = 64.0;
  73790. _this.sourceLight = null;
  73791. _this.hdrMinimumLuminance = 1.0;
  73792. _this.hdrDecreaseRate = 0.5;
  73793. _this.hdrIncreaseRate = 0.5;
  73794. _this.lensColorTexture = null;
  73795. _this.lensFlareStrength = 20.0;
  73796. _this.lensFlareGhostDispersal = 1.4;
  73797. _this.lensFlareHaloWidth = 0.7;
  73798. _this.lensFlareDistortionStrength = 16.0;
  73799. _this.lensStarTexture = null;
  73800. _this.lensFlareDirtTexture = null;
  73801. _this.depthOfFieldDistance = 10.0;
  73802. _this.depthOfFieldBlurWidth = 64.0;
  73803. _this.motionStrength = 1.0;
  73804. // IAnimatable
  73805. _this.animations = [];
  73806. _this._currentDepthOfFieldSource = null;
  73807. _this._hdrCurrentLuminance = 1.0;
  73808. // Getters and setters
  73809. _this._bloomEnabled = true;
  73810. _this._depthOfFieldEnabled = false;
  73811. _this._vlsEnabled = false;
  73812. _this._lensFlareEnabled = false;
  73813. _this._hdrEnabled = false;
  73814. _this._motionBlurEnabled = false;
  73815. _this._motionBlurSamples = 64.0;
  73816. _this._volumetricLightStepsCount = 50.0;
  73817. _this._cameras = cameras || [];
  73818. // Initialize
  73819. _this._scene = scene;
  73820. _this._basePostProcess = originalPostProcess;
  73821. _this._ratio = ratio;
  73822. // Misc
  73823. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  73824. // Finish
  73825. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73826. _this._buildPipeline();
  73827. return _this;
  73828. }
  73829. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  73830. get: function () {
  73831. return this._bloomEnabled;
  73832. },
  73833. set: function (enabled) {
  73834. if (this._bloomEnabled === enabled) {
  73835. return;
  73836. }
  73837. this._bloomEnabled = enabled;
  73838. this._buildPipeline();
  73839. },
  73840. enumerable: true,
  73841. configurable: true
  73842. });
  73843. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  73844. get: function () {
  73845. return this._depthOfFieldEnabled;
  73846. },
  73847. set: function (enabled) {
  73848. if (this._depthOfFieldEnabled === enabled) {
  73849. return;
  73850. }
  73851. this._depthOfFieldEnabled = enabled;
  73852. this._buildPipeline();
  73853. },
  73854. enumerable: true,
  73855. configurable: true
  73856. });
  73857. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  73858. get: function () {
  73859. return this._lensFlareEnabled;
  73860. },
  73861. set: function (enabled) {
  73862. if (this._lensFlareEnabled === enabled) {
  73863. return;
  73864. }
  73865. this._lensFlareEnabled = enabled;
  73866. this._buildPipeline();
  73867. },
  73868. enumerable: true,
  73869. configurable: true
  73870. });
  73871. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  73872. get: function () {
  73873. return this._hdrEnabled;
  73874. },
  73875. set: function (enabled) {
  73876. if (this._hdrEnabled === enabled) {
  73877. return;
  73878. }
  73879. this._hdrEnabled = enabled;
  73880. this._buildPipeline();
  73881. },
  73882. enumerable: true,
  73883. configurable: true
  73884. });
  73885. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  73886. get: function () {
  73887. return this._vlsEnabled;
  73888. },
  73889. set: function (enabled) {
  73890. if (this._vlsEnabled === enabled) {
  73891. return;
  73892. }
  73893. if (enabled) {
  73894. var geometry = this._scene.enableGeometryBufferRenderer();
  73895. if (!geometry) {
  73896. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  73897. return;
  73898. }
  73899. }
  73900. this._vlsEnabled = enabled;
  73901. this._buildPipeline();
  73902. },
  73903. enumerable: true,
  73904. configurable: true
  73905. });
  73906. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  73907. get: function () {
  73908. return this._motionBlurEnabled;
  73909. },
  73910. set: function (enabled) {
  73911. if (this._motionBlurEnabled === enabled) {
  73912. return;
  73913. }
  73914. this._motionBlurEnabled = enabled;
  73915. this._buildPipeline();
  73916. },
  73917. enumerable: true,
  73918. configurable: true
  73919. });
  73920. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  73921. get: function () {
  73922. return this._volumetricLightStepsCount;
  73923. },
  73924. set: function (count) {
  73925. if (this.volumetricLightPostProcess) {
  73926. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  73927. }
  73928. this._volumetricLightStepsCount = count;
  73929. },
  73930. enumerable: true,
  73931. configurable: true
  73932. });
  73933. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  73934. get: function () {
  73935. return this._motionBlurSamples;
  73936. },
  73937. set: function (samples) {
  73938. if (this.motionBlurPostProcess) {
  73939. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  73940. }
  73941. this._motionBlurSamples = samples;
  73942. },
  73943. enumerable: true,
  73944. configurable: true
  73945. });
  73946. StandardRenderingPipeline.prototype._buildPipeline = function () {
  73947. var _this = this;
  73948. var ratio = this._ratio;
  73949. var scene = this._scene;
  73950. this._disposePostProcesses();
  73951. this._reset();
  73952. // Create pass post-process
  73953. if (!this._basePostProcess) {
  73954. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  73955. this.originalPostProcess.onApply = function (effect) {
  73956. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  73957. };
  73958. }
  73959. else {
  73960. this.originalPostProcess = this._basePostProcess;
  73961. }
  73962. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  73963. this._currentDepthOfFieldSource = this.originalPostProcess;
  73964. if (this._bloomEnabled) {
  73965. // Create down sample X4 post-process
  73966. this._createDownSampleX4PostProcess(scene, ratio / 2);
  73967. // Create bright pass post-process
  73968. this._createBrightPassPostProcess(scene, ratio / 2);
  73969. // Create gaussian blur post-processes (down sampling blurs)
  73970. this._createBlurPostProcesses(scene, ratio / 4, 1);
  73971. // Create texture adder post-process
  73972. this._createTextureAdderPostProcess(scene, ratio);
  73973. // Create depth-of-field source post-process
  73974. 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);
  73975. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  73976. }
  73977. if (this._vlsEnabled) {
  73978. // Create volumetric light
  73979. this._createVolumetricLightPostProcess(scene, ratio);
  73980. // Create volumetric light final post-process
  73981. 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);
  73982. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  73983. }
  73984. if (this._lensFlareEnabled) {
  73985. // Create lens flare post-process
  73986. this._createLensFlarePostProcess(scene, ratio);
  73987. // Create depth-of-field source post-process post lens-flare and disable it now
  73988. 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);
  73989. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  73990. }
  73991. if (this._hdrEnabled) {
  73992. // Create luminance
  73993. this._createLuminancePostProcesses(scene, this._floatTextureType);
  73994. // Create HDR
  73995. this._createHdrPostProcess(scene, ratio);
  73996. // Create depth-of-field source post-process post hdr and disable it now
  73997. 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);
  73998. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  73999. }
  74000. if (this._depthOfFieldEnabled) {
  74001. // Create gaussian blur used by depth-of-field
  74002. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  74003. // Create depth-of-field post-process
  74004. this._createDepthOfFieldPostProcess(scene, ratio);
  74005. }
  74006. if (this._motionBlurEnabled) {
  74007. // Create motion blur post-process
  74008. this._createMotionBlurPostProcess(scene, ratio);
  74009. }
  74010. if (this._cameras !== null) {
  74011. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  74012. }
  74013. };
  74014. // Down Sample X4 Post-Processs
  74015. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  74016. var _this = this;
  74017. var downSampleX4Offsets = new Array(32);
  74018. 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);
  74019. this.downSampleX4PostProcess.onApply = function (effect) {
  74020. var id = 0;
  74021. var width = _this.downSampleX4PostProcess.width;
  74022. var height = _this.downSampleX4PostProcess.height;
  74023. for (var i = -2; i < 2; i++) {
  74024. for (var j = -2; j < 2; j++) {
  74025. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  74026. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  74027. id += 2;
  74028. }
  74029. }
  74030. effect.setArray2("dsOffsets", downSampleX4Offsets);
  74031. };
  74032. // Add to pipeline
  74033. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  74034. };
  74035. // Brightpass Post-Process
  74036. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  74037. var _this = this;
  74038. var brightOffsets = new Array(8);
  74039. 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);
  74040. this.brightPassPostProcess.onApply = function (effect) {
  74041. var sU = (1.0 / _this.brightPassPostProcess.width);
  74042. var sV = (1.0 / _this.brightPassPostProcess.height);
  74043. brightOffsets[0] = -0.5 * sU;
  74044. brightOffsets[1] = 0.5 * sV;
  74045. brightOffsets[2] = 0.5 * sU;
  74046. brightOffsets[3] = 0.5 * sV;
  74047. brightOffsets[4] = -0.5 * sU;
  74048. brightOffsets[5] = -0.5 * sV;
  74049. brightOffsets[6] = 0.5 * sU;
  74050. brightOffsets[7] = -0.5 * sV;
  74051. effect.setArray2("dsOffsets", brightOffsets);
  74052. effect.setFloat("brightThreshold", _this.brightThreshold);
  74053. };
  74054. // Add to pipeline
  74055. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  74056. };
  74057. // Create blur H&V post-processes
  74058. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  74059. var _this = this;
  74060. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  74061. var engine = scene.getEngine();
  74062. 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);
  74063. 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);
  74064. blurX.onActivateObservable.add(function () {
  74065. var dw = blurX.width / engine.getRenderWidth();
  74066. blurX.kernel = _this[blurWidthKey] * dw;
  74067. });
  74068. blurY.onActivateObservable.add(function () {
  74069. var dw = blurY.height / engine.getRenderHeight();
  74070. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  74071. });
  74072. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  74073. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  74074. this.blurHPostProcesses.push(blurX);
  74075. this.blurVPostProcesses.push(blurY);
  74076. };
  74077. // Create texture adder post-process
  74078. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  74079. var _this = this;
  74080. 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);
  74081. this.textureAdderPostProcess.onApply = function (effect) {
  74082. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  74083. effect.setTexture("lensSampler", _this.lensTexture);
  74084. effect.setFloat("exposure", _this.exposure);
  74085. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  74086. };
  74087. // Add to pipeline
  74088. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  74089. };
  74090. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  74091. var _this = this;
  74092. var geometryRenderer = scene.enableGeometryBufferRenderer();
  74093. geometryRenderer.enablePosition = true;
  74094. var geometry = geometryRenderer.getGBuffer();
  74095. // Base post-process
  74096. 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));
  74097. var depthValues = BABYLON.Vector2.Zero();
  74098. this.volumetricLightPostProcess.onApply = function (effect) {
  74099. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  74100. var generator = _this.sourceLight.getShadowGenerator();
  74101. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  74102. effect.setTexture("positionSampler", geometry.textures[2]);
  74103. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  74104. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  74105. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  74106. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  74107. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  74108. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  74109. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  74110. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  74111. effect.setVector2("depthValues", depthValues);
  74112. }
  74113. };
  74114. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  74115. // Smooth
  74116. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  74117. // Merge
  74118. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  74119. this.volumetricLightMergePostProces.onApply = function (effect) {
  74120. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  74121. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  74122. };
  74123. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  74124. };
  74125. // Create luminance
  74126. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  74127. var _this = this;
  74128. // Create luminance
  74129. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  74130. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  74131. var offsets = [];
  74132. this.luminancePostProcess.onApply = function (effect) {
  74133. var sU = (1.0 / _this.luminancePostProcess.width);
  74134. var sV = (1.0 / _this.luminancePostProcess.height);
  74135. offsets[0] = -0.5 * sU;
  74136. offsets[1] = 0.5 * sV;
  74137. offsets[2] = 0.5 * sU;
  74138. offsets[3] = 0.5 * sV;
  74139. offsets[4] = -0.5 * sU;
  74140. offsets[5] = -0.5 * sV;
  74141. offsets[6] = 0.5 * sU;
  74142. offsets[7] = -0.5 * sV;
  74143. effect.setArray2("lumOffsets", offsets);
  74144. };
  74145. // Add to pipeline
  74146. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  74147. // Create down sample luminance
  74148. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  74149. var size = Math.pow(3, i);
  74150. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  74151. if (i === 0) {
  74152. defines += "#define FINAL_DOWN_SAMPLER";
  74153. }
  74154. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  74155. this.luminanceDownSamplePostProcesses.push(postProcess);
  74156. }
  74157. // Create callbacks and add effects
  74158. var lastLuminance = this.luminancePostProcess;
  74159. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  74160. var downSampleOffsets = new Array(18);
  74161. pp.onApply = function (effect) {
  74162. if (!lastLuminance) {
  74163. return;
  74164. }
  74165. var id = 0;
  74166. for (var x = -1; x < 2; x++) {
  74167. for (var y = -1; y < 2; y++) {
  74168. downSampleOffsets[id] = x / lastLuminance.width;
  74169. downSampleOffsets[id + 1] = y / lastLuminance.height;
  74170. id += 2;
  74171. }
  74172. }
  74173. effect.setArray2("dsOffsets", downSampleOffsets);
  74174. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  74175. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74176. lastLuminance = _this.luminancePostProcess;
  74177. }
  74178. else {
  74179. lastLuminance = pp;
  74180. }
  74181. };
  74182. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74183. pp.onAfterRender = function (effect) {
  74184. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  74185. 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);
  74186. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  74187. };
  74188. }
  74189. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  74190. });
  74191. };
  74192. // Create HDR post-process
  74193. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  74194. var _this = this;
  74195. 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);
  74196. var outputLiminance = 1;
  74197. var time = 0;
  74198. var lastTime = 0;
  74199. this.hdrPostProcess.onApply = function (effect) {
  74200. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  74201. time += scene.getEngine().getDeltaTime();
  74202. if (outputLiminance < 0) {
  74203. outputLiminance = _this._hdrCurrentLuminance;
  74204. }
  74205. else {
  74206. var dt = (lastTime - time) / 1000.0;
  74207. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  74208. outputLiminance += _this.hdrDecreaseRate * dt;
  74209. }
  74210. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  74211. outputLiminance -= _this.hdrIncreaseRate * dt;
  74212. }
  74213. else {
  74214. outputLiminance = _this._hdrCurrentLuminance;
  74215. }
  74216. }
  74217. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  74218. effect.setFloat("averageLuminance", outputLiminance);
  74219. lastTime = time;
  74220. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  74221. };
  74222. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  74223. };
  74224. // Create lens flare post-process
  74225. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  74226. var _this = this;
  74227. 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);
  74228. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  74229. this._createBlurPostProcesses(scene, ratio / 4, 2);
  74230. 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);
  74231. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  74232. var resolution = new BABYLON.Vector2(0, 0);
  74233. // Lens flare
  74234. this.lensFlarePostProcess.onApply = function (effect) {
  74235. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  74236. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  74237. effect.setFloat("strength", _this.lensFlareStrength);
  74238. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  74239. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  74240. // Shift
  74241. resolution.x = _this.lensFlarePostProcess.width;
  74242. resolution.y = _this.lensFlarePostProcess.height;
  74243. effect.setVector2("resolution", resolution);
  74244. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  74245. };
  74246. // Compose
  74247. 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);
  74248. 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);
  74249. this.lensFlareComposePostProcess.onApply = function (effect) {
  74250. if (!_this._scene.activeCamera) {
  74251. return;
  74252. }
  74253. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  74254. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  74255. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  74256. // Lens start rotation matrix
  74257. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  74258. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  74259. 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));
  74260. camRot *= 4.0;
  74261. 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);
  74262. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  74263. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  74264. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  74265. };
  74266. };
  74267. // Create depth-of-field post-process
  74268. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  74269. var _this = this;
  74270. 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);
  74271. this.depthOfFieldPostProcess.onApply = function (effect) {
  74272. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  74273. effect.setTexture("depthSampler", _this._getDepthTexture());
  74274. effect.setFloat("distance", _this.depthOfFieldDistance);
  74275. };
  74276. // Add to pipeline
  74277. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  74278. };
  74279. // Create motion blur post-process
  74280. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  74281. var _this = this;
  74282. 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);
  74283. var motionScale = 0;
  74284. var prevViewProjection = BABYLON.Matrix.Identity();
  74285. var invViewProjection = BABYLON.Matrix.Identity();
  74286. var viewProjection = BABYLON.Matrix.Identity();
  74287. var screenSize = BABYLON.Vector2.Zero();
  74288. this.motionBlurPostProcess.onApply = function (effect) {
  74289. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  74290. viewProjection.invertToRef(invViewProjection);
  74291. effect.setMatrix("inverseViewProjection", invViewProjection);
  74292. effect.setMatrix("prevViewProjection", prevViewProjection);
  74293. prevViewProjection = viewProjection;
  74294. screenSize.x = _this.motionBlurPostProcess.width;
  74295. screenSize.y = _this.motionBlurPostProcess.height;
  74296. effect.setVector2("screenSize", screenSize);
  74297. motionScale = scene.getEngine().getFps() / 60.0;
  74298. effect.setFloat("motionScale", motionScale);
  74299. effect.setFloat("motionStrength", _this.motionStrength);
  74300. effect.setTexture("depthSampler", _this._getDepthTexture());
  74301. };
  74302. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  74303. };
  74304. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  74305. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  74306. var renderer = this._scene.enableGeometryBufferRenderer();
  74307. return renderer.getGBuffer().textures[0];
  74308. }
  74309. return this._scene.enableDepthRenderer().getDepthMap();
  74310. };
  74311. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  74312. for (var i = 0; i < this._cameras.length; i++) {
  74313. var camera = this._cameras[i];
  74314. if (this.originalPostProcess) {
  74315. this.originalPostProcess.dispose(camera);
  74316. }
  74317. if (this.downSampleX4PostProcess) {
  74318. this.downSampleX4PostProcess.dispose(camera);
  74319. }
  74320. if (this.brightPassPostProcess) {
  74321. this.brightPassPostProcess.dispose(camera);
  74322. }
  74323. if (this.textureAdderPostProcess) {
  74324. this.textureAdderPostProcess.dispose(camera);
  74325. }
  74326. if (this.textureAdderFinalPostProcess) {
  74327. this.textureAdderFinalPostProcess.dispose(camera);
  74328. }
  74329. if (this.volumetricLightPostProcess) {
  74330. this.volumetricLightPostProcess.dispose(camera);
  74331. }
  74332. if (this.volumetricLightSmoothXPostProcess) {
  74333. this.volumetricLightSmoothXPostProcess.dispose(camera);
  74334. }
  74335. if (this.volumetricLightSmoothYPostProcess) {
  74336. this.volumetricLightSmoothYPostProcess.dispose(camera);
  74337. }
  74338. if (this.volumetricLightMergePostProces) {
  74339. this.volumetricLightMergePostProces.dispose(camera);
  74340. }
  74341. if (this.volumetricLightFinalPostProcess) {
  74342. this.volumetricLightFinalPostProcess.dispose(camera);
  74343. }
  74344. if (this.lensFlarePostProcess) {
  74345. this.lensFlarePostProcess.dispose(camera);
  74346. }
  74347. if (this.lensFlareComposePostProcess) {
  74348. this.lensFlareComposePostProcess.dispose(camera);
  74349. }
  74350. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  74351. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  74352. }
  74353. if (this.luminancePostProcess) {
  74354. this.luminancePostProcess.dispose(camera);
  74355. }
  74356. if (this.hdrPostProcess) {
  74357. this.hdrPostProcess.dispose(camera);
  74358. }
  74359. if (this.hdrFinalPostProcess) {
  74360. this.hdrFinalPostProcess.dispose(camera);
  74361. }
  74362. if (this.depthOfFieldPostProcess) {
  74363. this.depthOfFieldPostProcess.dispose(camera);
  74364. }
  74365. if (this.motionBlurPostProcess) {
  74366. this.motionBlurPostProcess.dispose(camera);
  74367. }
  74368. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  74369. this.blurHPostProcesses[j].dispose(camera);
  74370. }
  74371. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  74372. this.blurVPostProcesses[j].dispose(camera);
  74373. }
  74374. }
  74375. this.originalPostProcess = null;
  74376. this.downSampleX4PostProcess = null;
  74377. this.brightPassPostProcess = null;
  74378. this.textureAdderPostProcess = null;
  74379. this.textureAdderFinalPostProcess = null;
  74380. this.volumetricLightPostProcess = null;
  74381. this.volumetricLightSmoothXPostProcess = null;
  74382. this.volumetricLightSmoothYPostProcess = null;
  74383. this.volumetricLightMergePostProces = null;
  74384. this.volumetricLightFinalPostProcess = null;
  74385. this.lensFlarePostProcess = null;
  74386. this.lensFlareComposePostProcess = null;
  74387. this.luminancePostProcess = null;
  74388. this.hdrPostProcess = null;
  74389. this.hdrFinalPostProcess = null;
  74390. this.depthOfFieldPostProcess = null;
  74391. this.motionBlurPostProcess = null;
  74392. this.luminanceDownSamplePostProcesses = [];
  74393. this.blurHPostProcesses = [];
  74394. this.blurVPostProcesses = [];
  74395. };
  74396. /**
  74397. * Dispose of the pipeline and stop all post processes
  74398. */
  74399. StandardRenderingPipeline.prototype.dispose = function () {
  74400. this._disposePostProcesses();
  74401. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  74402. _super.prototype.dispose.call(this);
  74403. };
  74404. /**
  74405. * Serialize the rendering pipeline (Used when exporting)
  74406. * @returns the serialized object
  74407. */
  74408. StandardRenderingPipeline.prototype.serialize = function () {
  74409. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  74410. if (this.sourceLight) {
  74411. serializationObject.sourceLightId = this.sourceLight.id;
  74412. }
  74413. serializationObject.customType = "StandardRenderingPipeline";
  74414. return serializationObject;
  74415. };
  74416. /**
  74417. * Parse the serialized pipeline
  74418. * @param source Source pipeline.
  74419. * @param scene The scene to load the pipeline to.
  74420. * @param rootUrl The URL of the serialized pipeline.
  74421. * @returns An instantiated pipeline from the serialized object.
  74422. */
  74423. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  74424. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  74425. if (source.sourceLightId) {
  74426. p.sourceLight = scene.getLightByID(source.sourceLightId);
  74427. }
  74428. return p;
  74429. };
  74430. // Luminance steps
  74431. StandardRenderingPipeline.LuminanceSteps = 6;
  74432. __decorate([
  74433. BABYLON.serialize()
  74434. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  74435. __decorate([
  74436. BABYLON.serialize()
  74437. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  74438. __decorate([
  74439. BABYLON.serialize()
  74440. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  74441. __decorate([
  74442. BABYLON.serialize()
  74443. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  74444. __decorate([
  74445. BABYLON.serializeAsTexture("lensTexture")
  74446. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  74447. __decorate([
  74448. BABYLON.serialize()
  74449. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  74450. __decorate([
  74451. BABYLON.serialize()
  74452. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  74453. __decorate([
  74454. BABYLON.serialize()
  74455. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  74456. __decorate([
  74457. BABYLON.serialize()
  74458. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  74459. __decorate([
  74460. BABYLON.serialize()
  74461. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  74462. __decorate([
  74463. BABYLON.serialize()
  74464. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  74465. __decorate([
  74466. BABYLON.serializeAsTexture("lensColorTexture")
  74467. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  74468. __decorate([
  74469. BABYLON.serialize()
  74470. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  74471. __decorate([
  74472. BABYLON.serialize()
  74473. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  74474. __decorate([
  74475. BABYLON.serialize()
  74476. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  74477. __decorate([
  74478. BABYLON.serialize()
  74479. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  74480. __decorate([
  74481. BABYLON.serializeAsTexture("lensStarTexture")
  74482. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  74483. __decorate([
  74484. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  74485. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  74486. __decorate([
  74487. BABYLON.serialize()
  74488. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  74489. __decorate([
  74490. BABYLON.serialize()
  74491. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  74492. __decorate([
  74493. BABYLON.serialize()
  74494. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  74495. __decorate([
  74496. BABYLON.serialize()
  74497. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  74498. __decorate([
  74499. BABYLON.serialize()
  74500. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  74501. __decorate([
  74502. BABYLON.serialize()
  74503. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  74504. __decorate([
  74505. BABYLON.serialize()
  74506. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  74507. __decorate([
  74508. BABYLON.serialize()
  74509. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  74510. __decorate([
  74511. BABYLON.serialize()
  74512. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  74513. __decorate([
  74514. BABYLON.serialize()
  74515. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  74516. __decorate([
  74517. BABYLON.serialize()
  74518. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  74519. __decorate([
  74520. BABYLON.serialize()
  74521. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  74522. return StandardRenderingPipeline;
  74523. }(BABYLON.PostProcessRenderPipeline));
  74524. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  74525. })(BABYLON || (BABYLON = {}));
  74526. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  74527. var BABYLON;
  74528. (function (BABYLON) {
  74529. var FxaaPostProcess = /** @class */ (function (_super) {
  74530. __extends(FxaaPostProcess, _super);
  74531. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  74532. if (camera === void 0) { camera = null; }
  74533. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74534. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  74535. var defines = _this._getDefines();
  74536. _this.updateEffect(defines);
  74537. _this.onApplyObservable.add(function (effect) {
  74538. var texelSize = _this.texelSize;
  74539. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  74540. });
  74541. return _this;
  74542. }
  74543. FxaaPostProcess.prototype._getDefines = function () {
  74544. var engine = this.getEngine();
  74545. if (!engine) {
  74546. return null;
  74547. }
  74548. var glInfo = engine.getGlInfo();
  74549. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  74550. return "#define MALI 1\n";
  74551. }
  74552. return null;
  74553. };
  74554. return FxaaPostProcess;
  74555. }(BABYLON.PostProcess));
  74556. BABYLON.FxaaPostProcess = FxaaPostProcess;
  74557. })(BABYLON || (BABYLON = {}));
  74558. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  74559. var BABYLON;
  74560. (function (BABYLON) {
  74561. /**
  74562. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  74563. */
  74564. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  74565. __extends(ChromaticAberrationPostProcess, _super);
  74566. /**
  74567. * Creates a new instance ChromaticAberrationPostProcess
  74568. * @param name The name of the effect.
  74569. * @param screenWidth The width of the screen to apply the effect on.
  74570. * @param screenHeight The height of the screen to apply the effect on.
  74571. * @param options The required width/height ratio to downsize to before computing the render pass.
  74572. * @param camera The camera to apply the render pass to.
  74573. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74574. * @param engine The engine which the post process will be applied. (default: current engine)
  74575. * @param reusable If the post process can be reused on the same frame. (default: false)
  74576. * @param textureType Type of textures used when performing the post process. (default: 0)
  74577. * @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)
  74578. */
  74579. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74580. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74581. if (blockCompilation === void 0) { blockCompilation = false; }
  74582. 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;
  74583. /**
  74584. * The amount of seperation of rgb channels (default: 30)
  74585. */
  74586. _this.aberrationAmount = 30;
  74587. /**
  74588. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  74589. */
  74590. _this.radialIntensity = 0;
  74591. /**
  74592. * 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))
  74593. */
  74594. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  74595. /**
  74596. * 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))
  74597. */
  74598. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  74599. _this.onApplyObservable.add(function (effect) {
  74600. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  74601. effect.setFloat('screen_width', screenWidth);
  74602. effect.setFloat('screen_height', screenHeight);
  74603. effect.setFloat('radialIntensity', _this.radialIntensity);
  74604. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  74605. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  74606. });
  74607. return _this;
  74608. }
  74609. return ChromaticAberrationPostProcess;
  74610. }(BABYLON.PostProcess));
  74611. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  74612. })(BABYLON || (BABYLON = {}));
  74613. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  74614. var BABYLON;
  74615. (function (BABYLON) {
  74616. /**
  74617. * The GrainPostProcess adds noise to the image at mid luminance levels
  74618. */
  74619. var GrainPostProcess = /** @class */ (function (_super) {
  74620. __extends(GrainPostProcess, _super);
  74621. /**
  74622. * Creates a new instance of @see GrainPostProcess
  74623. * @param name The name of the effect.
  74624. * @param options The required width/height ratio to downsize to before computing the render pass.
  74625. * @param camera The camera to apply the render pass to.
  74626. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74627. * @param engine The engine which the post process will be applied. (default: current engine)
  74628. * @param reusable If the post process can be reused on the same frame. (default: false)
  74629. * @param textureType Type of textures used when performing the post process. (default: 0)
  74630. * @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)
  74631. */
  74632. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74633. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74634. if (blockCompilation === void 0) { blockCompilation = false; }
  74635. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  74636. /**
  74637. * The intensity of the grain added (default: 30)
  74638. */
  74639. _this.intensity = 30;
  74640. /**
  74641. * If the grain should be randomized on every frame
  74642. */
  74643. _this.animated = false;
  74644. _this.onApplyObservable.add(function (effect) {
  74645. effect.setFloat('intensity', _this.intensity);
  74646. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  74647. });
  74648. return _this;
  74649. }
  74650. return GrainPostProcess;
  74651. }(BABYLON.PostProcess));
  74652. BABYLON.GrainPostProcess = GrainPostProcess;
  74653. })(BABYLON || (BABYLON = {}));
  74654. //# sourceMappingURL=babylon.grainPostProcess.js.map
  74655. var BABYLON;
  74656. (function (BABYLON) {
  74657. /**
  74658. * The SharpenPostProcess applies a sharpen kernel to every pixel
  74659. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  74660. */
  74661. var SharpenPostProcess = /** @class */ (function (_super) {
  74662. __extends(SharpenPostProcess, _super);
  74663. /**
  74664. * Creates a new instance ConvolutionPostProcess
  74665. * @param name The name of the effect.
  74666. * @param options The required width/height ratio to downsize to before computing the render pass.
  74667. * @param camera The camera to apply the render pass to.
  74668. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74669. * @param engine The engine which the post process will be applied. (default: current engine)
  74670. * @param reusable If the post process can be reused on the same frame. (default: false)
  74671. * @param textureType Type of textures used when performing the post process. (default: 0)
  74672. * @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)
  74673. */
  74674. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74675. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74676. if (blockCompilation === void 0) { blockCompilation = false; }
  74677. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  74678. /**
  74679. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  74680. */
  74681. _this.colorAmount = 1.0;
  74682. /**
  74683. * How much sharpness should be applied (default: 0.3)
  74684. */
  74685. _this.edgeAmount = 0.3;
  74686. _this.onApply = function (effect) {
  74687. effect.setFloat2("screenSize", _this.width, _this.height);
  74688. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  74689. };
  74690. return _this;
  74691. }
  74692. return SharpenPostProcess;
  74693. }(BABYLON.PostProcess));
  74694. BABYLON.SharpenPostProcess = SharpenPostProcess;
  74695. })(BABYLON || (BABYLON = {}));
  74696. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  74697. var BABYLON;
  74698. (function (BABYLON) {
  74699. /**
  74700. * The Blur Post Process which blurs an image based on a kernel and direction.
  74701. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  74702. */
  74703. var BlurPostProcess = /** @class */ (function (_super) {
  74704. __extends(BlurPostProcess, _super);
  74705. /**
  74706. * Creates a new instance BlurPostProcess
  74707. * @param name The name of the effect.
  74708. * @param direction The direction in which to blur the image.
  74709. * @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.
  74710. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  74711. * @param camera The camera to apply the render pass to.
  74712. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74713. * @param engine The engine which the post process will be applied. (default: current engine)
  74714. * @param reusable If the post process can be reused on the same frame. (default: false)
  74715. * @param textureType Type of textures used when performing the post process. (default: 0)
  74716. * @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)
  74717. */
  74718. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  74719. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  74720. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74721. if (defines === void 0) { defines = ""; }
  74722. if (blockCompilation === void 0) { blockCompilation = false; }
  74723. 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;
  74724. _this.direction = direction;
  74725. _this.blockCompilation = blockCompilation;
  74726. _this._packedFloat = false;
  74727. _this._staticDefines = "";
  74728. _this._staticDefines = defines;
  74729. _this.onApplyObservable.add(function (effect) {
  74730. if (_this._outputTexture) {
  74731. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  74732. }
  74733. else {
  74734. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  74735. }
  74736. });
  74737. _this.kernel = kernel;
  74738. return _this;
  74739. }
  74740. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  74741. /**
  74742. * Gets the length in pixels of the blur sample region
  74743. */
  74744. get: function () {
  74745. return this._idealKernel;
  74746. },
  74747. /**
  74748. * Sets the length in pixels of the blur sample region
  74749. */
  74750. set: function (v) {
  74751. if (this._idealKernel === v) {
  74752. return;
  74753. }
  74754. v = Math.max(v, 1);
  74755. this._idealKernel = v;
  74756. this._kernel = this._nearestBestKernel(v);
  74757. if (!this.blockCompilation) {
  74758. this._updateParameters();
  74759. }
  74760. },
  74761. enumerable: true,
  74762. configurable: true
  74763. });
  74764. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  74765. /**
  74766. * Gets wether or not the blur is unpacking/repacking floats
  74767. */
  74768. get: function () {
  74769. return this._packedFloat;
  74770. },
  74771. /**
  74772. * Sets wether or not the blur needs to unpack/repack floats
  74773. */
  74774. set: function (v) {
  74775. if (this._packedFloat === v) {
  74776. return;
  74777. }
  74778. this._packedFloat = v;
  74779. if (!this.blockCompilation) {
  74780. this._updateParameters();
  74781. }
  74782. },
  74783. enumerable: true,
  74784. configurable: true
  74785. });
  74786. /**
  74787. * Updates the effect with the current post process compile time values and recompiles the shader.
  74788. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  74789. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  74790. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  74791. * @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
  74792. * @param onCompiled Called when the shader has been compiled.
  74793. * @param onError Called if there is an error when compiling a shader.
  74794. */
  74795. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  74796. if (defines === void 0) { defines = null; }
  74797. if (uniforms === void 0) { uniforms = null; }
  74798. if (samplers === void 0) { samplers = null; }
  74799. this._updateParameters(onCompiled, onError);
  74800. };
  74801. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  74802. // Generate sampling offsets and weights
  74803. var N = this._kernel;
  74804. var centerIndex = (N - 1) / 2;
  74805. // Generate Gaussian sampling weights over kernel
  74806. var offsets = [];
  74807. var weights = [];
  74808. var totalWeight = 0;
  74809. for (var i = 0; i < N; i++) {
  74810. var u = i / (N - 1);
  74811. var w = this._gaussianWeight(u * 2.0 - 1);
  74812. offsets[i] = (i - centerIndex);
  74813. weights[i] = w;
  74814. totalWeight += w;
  74815. }
  74816. // Normalize weights
  74817. for (var i = 0; i < weights.length; i++) {
  74818. weights[i] /= totalWeight;
  74819. }
  74820. // Optimize: combine samples to take advantage of hardware linear sampling
  74821. // Walk from left to center, combining pairs (symmetrically)
  74822. var linearSamplingWeights = [];
  74823. var linearSamplingOffsets = [];
  74824. var linearSamplingMap = [];
  74825. for (var i = 0; i <= centerIndex; i += 2) {
  74826. var j = Math.min(i + 1, Math.floor(centerIndex));
  74827. var singleCenterSample = i === j;
  74828. if (singleCenterSample) {
  74829. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  74830. }
  74831. else {
  74832. var sharedCell = j === centerIndex;
  74833. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  74834. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  74835. if (offsetLinear === 0) {
  74836. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  74837. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  74838. }
  74839. else {
  74840. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  74841. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  74842. }
  74843. }
  74844. }
  74845. for (var i = 0; i < linearSamplingMap.length; i++) {
  74846. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  74847. linearSamplingWeights[i] = linearSamplingMap[i].w;
  74848. }
  74849. // Replace with optimized
  74850. offsets = linearSamplingOffsets;
  74851. weights = linearSamplingWeights;
  74852. // Generate shaders
  74853. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  74854. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  74855. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  74856. var defines = "";
  74857. defines += this._staticDefines;
  74858. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  74859. if (this._staticDefines.indexOf("DOF") != -1) {
  74860. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  74861. varyingCount--;
  74862. }
  74863. for (var i = 0; i < varyingCount; i++) {
  74864. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  74865. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  74866. }
  74867. var depCount = 0;
  74868. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  74869. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  74870. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  74871. depCount++;
  74872. }
  74873. if (this.packedFloat) {
  74874. defines += "#define PACKEDFLOAT 1";
  74875. }
  74876. this.blockCompilation = false;
  74877. _super.prototype.updateEffect.call(this, defines, null, null, {
  74878. varyingCount: varyingCount,
  74879. depCount: depCount
  74880. }, onCompiled, onError);
  74881. };
  74882. /**
  74883. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  74884. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  74885. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  74886. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  74887. * The gaps between physical kernels are compensated for in the weighting of the samples
  74888. * @param idealKernel Ideal blur kernel.
  74889. * @return Nearest best kernel.
  74890. */
  74891. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  74892. var v = Math.round(idealKernel);
  74893. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  74894. var k = _a[_i];
  74895. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  74896. return Math.max(k, 3);
  74897. }
  74898. }
  74899. return Math.max(v, 3);
  74900. };
  74901. /**
  74902. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  74903. * @param x The point on the Gaussian distribution to sample.
  74904. * @return the value of the Gaussian function at x.
  74905. */
  74906. BlurPostProcess.prototype._gaussianWeight = function (x) {
  74907. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  74908. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  74909. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  74910. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  74911. // truncated at around 1.3% of peak strength.
  74912. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  74913. var sigma = (1 / 3);
  74914. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  74915. var exponent = -((x * x) / (2.0 * sigma * sigma));
  74916. var weight = (1.0 / denominator) * Math.exp(exponent);
  74917. return weight;
  74918. };
  74919. /**
  74920. * Generates a string that can be used as a floating point number in GLSL.
  74921. * @param x Value to print.
  74922. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  74923. * @return GLSL float string.
  74924. */
  74925. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  74926. if (decimalFigures === void 0) { decimalFigures = 8; }
  74927. return x.toFixed(decimalFigures).replace(/0+$/, '');
  74928. };
  74929. return BlurPostProcess;
  74930. }(BABYLON.PostProcess));
  74931. BABYLON.BlurPostProcess = BlurPostProcess;
  74932. })(BABYLON || (BABYLON = {}));
  74933. //# sourceMappingURL=babylon.blurPostProcess.js.map
  74934. var BABYLON;
  74935. (function (BABYLON) {
  74936. /**
  74937. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  74938. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  74939. * based on samples that have a large difference in distance than the center pixel.
  74940. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  74941. */
  74942. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  74943. __extends(DepthOfFieldBlurPostProcess, _super);
  74944. /**
  74945. * Creates a new instance CircleOfConfusionPostProcess
  74946. * @param name The name of the effect.
  74947. * @param scene The scene the effect belongs to.
  74948. * @param direction The direction the blur should be applied.
  74949. * @param kernel The size of the kernel used to blur.
  74950. * @param options The required width/height ratio to downsize to before computing the render pass.
  74951. * @param camera The camera to apply the render pass to.
  74952. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  74953. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  74954. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74955. * @param engine The engine which the post process will be applied. (default: current engine)
  74956. * @param reusable If the post process can be reused on the same frame. (default: false)
  74957. * @param textureType Type of textures used when performing the post process. (default: 0)
  74958. * @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)
  74959. */
  74960. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  74961. if (imageToBlur === void 0) { imageToBlur = null; }
  74962. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  74963. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74964. if (blockCompilation === void 0) { blockCompilation = false; }
  74965. 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;
  74966. _this.direction = direction;
  74967. _this.onApplyObservable.add(function (effect) {
  74968. if (imageToBlur != null) {
  74969. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  74970. }
  74971. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  74972. if (scene.activeCamera) {
  74973. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  74974. }
  74975. });
  74976. return _this;
  74977. }
  74978. return DepthOfFieldBlurPostProcess;
  74979. }(BABYLON.BlurPostProcess));
  74980. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  74981. })(BABYLON || (BABYLON = {}));
  74982. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  74983. var BABYLON;
  74984. (function (BABYLON) {
  74985. /**
  74986. * Options to be set when merging outputs from the default pipeline.
  74987. */
  74988. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  74989. function DepthOfFieldMergePostProcessOptions() {
  74990. }
  74991. return DepthOfFieldMergePostProcessOptions;
  74992. }());
  74993. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  74994. /**
  74995. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  74996. */
  74997. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  74998. __extends(DepthOfFieldMergePostProcess, _super);
  74999. /**
  75000. * Creates a new instance of DepthOfFieldMergePostProcess
  75001. * @param name The name of the effect.
  75002. * @param originalFromInput Post process which's input will be used for the merge.
  75003. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  75004. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  75005. * @param options The required width/height ratio to downsize to before computing the render pass.
  75006. * @param camera The camera to apply the render pass to.
  75007. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75008. * @param engine The engine which the post process will be applied. (default: current engine)
  75009. * @param reusable If the post process can be reused on the same frame. (default: false)
  75010. * @param textureType Type of textures used when performing the post process. (default: 0)
  75011. * @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)
  75012. */
  75013. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75014. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75015. if (blockCompilation === void 0) { blockCompilation = false; }
  75016. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  75017. _this.blurSteps = blurSteps;
  75018. _this.onApplyObservable.add(function (effect) {
  75019. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  75020. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  75021. blurSteps.forEach(function (step, index) {
  75022. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  75023. });
  75024. });
  75025. if (!blockCompilation) {
  75026. _this.updateEffect();
  75027. }
  75028. return _this;
  75029. }
  75030. /**
  75031. * Updates the effect with the current post process compile time values and recompiles the shader.
  75032. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  75033. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  75034. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  75035. * @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
  75036. * @param onCompiled Called when the shader has been compiled.
  75037. * @param onError Called if there is an error when compiling a shader.
  75038. */
  75039. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  75040. if (defines === void 0) { defines = null; }
  75041. if (uniforms === void 0) { uniforms = null; }
  75042. if (samplers === void 0) { samplers = null; }
  75043. if (!defines) {
  75044. defines = "";
  75045. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  75046. }
  75047. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  75048. };
  75049. return DepthOfFieldMergePostProcess;
  75050. }(BABYLON.PostProcess));
  75051. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  75052. })(BABYLON || (BABYLON = {}));
  75053. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  75054. var BABYLON;
  75055. (function (BABYLON) {
  75056. /**
  75057. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  75058. */
  75059. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  75060. __extends(CircleOfConfusionPostProcess, _super);
  75061. /**
  75062. * Creates a new instance CircleOfConfusionPostProcess
  75063. * @param name The name of the effect.
  75064. * @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.
  75065. * @param options The required width/height ratio to downsize to before computing the render pass.
  75066. * @param camera The camera to apply the render pass to.
  75067. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75068. * @param engine The engine which the post process will be applied. (default: current engine)
  75069. * @param reusable If the post process can be reused on the same frame. (default: false)
  75070. * @param textureType Type of textures used when performing the post process. (default: 0)
  75071. * @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)
  75072. */
  75073. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75074. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75075. if (blockCompilation === void 0) { blockCompilation = false; }
  75076. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75077. /**
  75078. * 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.
  75079. */
  75080. _this.lensSize = 50;
  75081. /**
  75082. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  75083. */
  75084. _this.fStop = 1.4;
  75085. /**
  75086. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  75087. */
  75088. _this.focusDistance = 2000;
  75089. /**
  75090. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  75091. */
  75092. _this.focalLength = 50;
  75093. _this._depthTexture = null;
  75094. _this._depthTexture = depthTexture;
  75095. _this.onApplyObservable.add(function (effect) {
  75096. if (!_this._depthTexture) {
  75097. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  75098. return;
  75099. }
  75100. effect.setTexture("depthSampler", _this._depthTexture);
  75101. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  75102. var aperture = _this.lensSize / _this.fStop;
  75103. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  75104. effect.setFloat('focusDistance', _this.focusDistance);
  75105. effect.setFloat('cocPrecalculation', cocPrecalculation);
  75106. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  75107. });
  75108. return _this;
  75109. }
  75110. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  75111. /**
  75112. * 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.
  75113. */
  75114. set: function (value) {
  75115. this._depthTexture = value;
  75116. },
  75117. enumerable: true,
  75118. configurable: true
  75119. });
  75120. return CircleOfConfusionPostProcess;
  75121. }(BABYLON.PostProcess));
  75122. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  75123. })(BABYLON || (BABYLON = {}));
  75124. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  75125. var BABYLON;
  75126. (function (BABYLON) {
  75127. /**
  75128. * Specifies the level of max blur that should be applied when using the depth of field effect
  75129. */
  75130. var DepthOfFieldEffectBlurLevel;
  75131. (function (DepthOfFieldEffectBlurLevel) {
  75132. /**
  75133. * Subtle blur
  75134. */
  75135. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  75136. /**
  75137. * Medium blur
  75138. */
  75139. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  75140. /**
  75141. * Large blur
  75142. */
  75143. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  75144. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  75145. ;
  75146. /**
  75147. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  75148. */
  75149. var DepthOfFieldEffect = /** @class */ (function (_super) {
  75150. __extends(DepthOfFieldEffect, _super);
  75151. /**
  75152. * Creates a new instance DepthOfFieldEffect
  75153. * @param scene The scene the effect belongs to.
  75154. * @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.
  75155. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  75156. * @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)
  75157. */
  75158. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  75159. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  75160. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  75161. if (blockCompilation === void 0) { blockCompilation = false; }
  75162. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  75163. return _this._effects;
  75164. }, true) || this;
  75165. /**
  75166. * Internal post processes in depth of field effect
  75167. */
  75168. _this._effects = [];
  75169. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  75170. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75171. // 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)
  75172. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  75173. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  75174. _this._depthOfFieldBlurY = [];
  75175. _this._depthOfFieldBlurX = [];
  75176. var blurCount = 1;
  75177. var kernelSize = 15;
  75178. switch (blurLevel) {
  75179. case DepthOfFieldEffectBlurLevel.High: {
  75180. blurCount = 3;
  75181. kernelSize = 51;
  75182. break;
  75183. }
  75184. case DepthOfFieldEffectBlurLevel.Medium: {
  75185. blurCount = 2;
  75186. kernelSize = 31;
  75187. break;
  75188. }
  75189. default: {
  75190. kernelSize = 15;
  75191. blurCount = 1;
  75192. break;
  75193. }
  75194. }
  75195. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  75196. var ratio = 1.0;
  75197. for (var i = 0; i < blurCount; i++) {
  75198. 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);
  75199. blurY.autoClear = false;
  75200. ratio = 0.75 / Math.pow(2, i);
  75201. 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);
  75202. blurX.autoClear = false;
  75203. _this._depthOfFieldBlurY.push(blurY);
  75204. _this._depthOfFieldBlurX.push(blurX);
  75205. }
  75206. // Set all post processes on the effect.
  75207. _this._effects = [_this._circleOfConfusion];
  75208. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  75209. _this._effects.push(_this._depthOfFieldBlurY[i]);
  75210. _this._effects.push(_this._depthOfFieldBlurX[i]);
  75211. }
  75212. // Merge blurred images with original image based on circleOfConfusion
  75213. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75214. _this._dofMerge.autoClear = false;
  75215. _this._effects.push(_this._dofMerge);
  75216. return _this;
  75217. }
  75218. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  75219. get: function () {
  75220. return this._circleOfConfusion.focalLength;
  75221. },
  75222. /**
  75223. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  75224. */
  75225. set: function (value) {
  75226. this._circleOfConfusion.focalLength = value;
  75227. },
  75228. enumerable: true,
  75229. configurable: true
  75230. });
  75231. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  75232. get: function () {
  75233. return this._circleOfConfusion.fStop;
  75234. },
  75235. /**
  75236. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  75237. */
  75238. set: function (value) {
  75239. this._circleOfConfusion.fStop = value;
  75240. },
  75241. enumerable: true,
  75242. configurable: true
  75243. });
  75244. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  75245. get: function () {
  75246. return this._circleOfConfusion.focusDistance;
  75247. },
  75248. /**
  75249. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  75250. */
  75251. set: function (value) {
  75252. this._circleOfConfusion.focusDistance = value;
  75253. },
  75254. enumerable: true,
  75255. configurable: true
  75256. });
  75257. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  75258. get: function () {
  75259. return this._circleOfConfusion.lensSize;
  75260. },
  75261. /**
  75262. * 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.
  75263. */
  75264. set: function (value) {
  75265. this._circleOfConfusion.lensSize = value;
  75266. },
  75267. enumerable: true,
  75268. configurable: true
  75269. });
  75270. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  75271. /**
  75272. * 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.
  75273. */
  75274. set: function (value) {
  75275. this._circleOfConfusion.depthTexture = value;
  75276. },
  75277. enumerable: true,
  75278. configurable: true
  75279. });
  75280. /**
  75281. * Disposes each of the internal effects for a given camera.
  75282. * @param camera The camera to dispose the effect on.
  75283. */
  75284. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  75285. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75286. this._effects[effectIndex].dispose(camera);
  75287. }
  75288. };
  75289. /**
  75290. * Internal
  75291. */
  75292. DepthOfFieldEffect.prototype._updateEffects = function () {
  75293. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75294. this._effects[effectIndex].updateEffect();
  75295. }
  75296. };
  75297. /**
  75298. * Internal
  75299. * @returns if all the contained post processes are ready.
  75300. */
  75301. DepthOfFieldEffect.prototype._isReady = function () {
  75302. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75303. if (!this._effects[effectIndex].isReady()) {
  75304. return false;
  75305. }
  75306. }
  75307. return true;
  75308. };
  75309. return DepthOfFieldEffect;
  75310. }(BABYLON.PostProcessRenderEffect));
  75311. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  75312. })(BABYLON || (BABYLON = {}));
  75313. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  75314. var BABYLON;
  75315. (function (BABYLON) {
  75316. /**
  75317. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  75318. */
  75319. var BloomMergePostProcess = /** @class */ (function (_super) {
  75320. __extends(BloomMergePostProcess, _super);
  75321. /**
  75322. * Creates a new instance of @see BloomMergePostProcess
  75323. * @param name The name of the effect.
  75324. * @param originalFromInput Post process which's input will be used for the merge.
  75325. * @param blurred Blurred highlights post process which's output will be used.
  75326. * @param weight Weight of the bloom to be added to the original input.
  75327. * @param options The required width/height ratio to downsize to before computing the render pass.
  75328. * @param camera The camera to apply the render pass to.
  75329. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75330. * @param engine The engine which the post process will be applied. (default: current engine)
  75331. * @param reusable If the post process can be reused on the same frame. (default: false)
  75332. * @param textureType Type of textures used when performing the post process. (default: 0)
  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 BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75336. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75337. if (blockCompilation === void 0) { blockCompilation = false; }
  75338. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  75339. _this.weight = weight;
  75340. _this.onApplyObservable.add(function (effect) {
  75341. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  75342. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  75343. effect.setFloat("bloomWeight", _this.weight);
  75344. });
  75345. if (!blockCompilation) {
  75346. _this.updateEffect();
  75347. }
  75348. return _this;
  75349. }
  75350. return BloomMergePostProcess;
  75351. }(BABYLON.PostProcess));
  75352. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  75353. })(BABYLON || (BABYLON = {}));
  75354. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  75355. var BABYLON;
  75356. (function (BABYLON) {
  75357. /**
  75358. * 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.
  75359. */
  75360. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  75361. __extends(ExtractHighlightsPostProcess, _super);
  75362. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75363. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75364. if (blockCompilation === void 0) { blockCompilation = false; }
  75365. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75366. /**
  75367. * The luminance threshold, pixels below this value will be set to black.
  75368. */
  75369. _this.threshold = 0.9;
  75370. /**
  75371. * Internal
  75372. */
  75373. _this._exposure = 1;
  75374. /**
  75375. * Post process which has the input texture to be used when performing highlight extraction
  75376. */
  75377. _this._inputPostProcess = null;
  75378. _this.onApplyObservable.add(function (effect) {
  75379. if (_this._inputPostProcess) {
  75380. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  75381. }
  75382. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  75383. effect.setFloat('exposure', _this._exposure);
  75384. });
  75385. return _this;
  75386. }
  75387. return ExtractHighlightsPostProcess;
  75388. }(BABYLON.PostProcess));
  75389. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  75390. })(BABYLON || (BABYLON = {}));
  75391. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  75392. var BABYLON;
  75393. (function (BABYLON) {
  75394. /**
  75395. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  75396. */
  75397. var BloomEffect = /** @class */ (function (_super) {
  75398. __extends(BloomEffect, _super);
  75399. /**
  75400. * Creates a new instance of @see BloomEffect
  75401. * @param scene The scene the effect belongs to.
  75402. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  75403. * @param bloomKernel The size of the kernel to be used when applying the blur.
  75404. * @param bloomWeight The the strength of bloom.
  75405. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  75406. * @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)
  75407. */
  75408. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  75409. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  75410. if (blockCompilation === void 0) { blockCompilation = false; }
  75411. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  75412. return _this._effects;
  75413. }, true) || this;
  75414. _this.bloomScale = bloomScale;
  75415. /**
  75416. * Internal
  75417. */
  75418. _this._effects = [];
  75419. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75420. _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);
  75421. _this._blurX.alwaysForcePOT = true;
  75422. _this._blurX.autoClear = false;
  75423. _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);
  75424. _this._blurY.alwaysForcePOT = true;
  75425. _this._blurY.autoClear = false;
  75426. _this.kernel = bloomKernel;
  75427. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  75428. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75429. _this._merge.autoClear = false;
  75430. _this._effects.push(_this._merge);
  75431. return _this;
  75432. }
  75433. Object.defineProperty(BloomEffect.prototype, "threshold", {
  75434. /**
  75435. * The luminance threshold to find bright areas of the image to bloom.
  75436. */
  75437. get: function () {
  75438. return this._downscale.threshold;
  75439. },
  75440. set: function (value) {
  75441. this._downscale.threshold = value;
  75442. },
  75443. enumerable: true,
  75444. configurable: true
  75445. });
  75446. Object.defineProperty(BloomEffect.prototype, "weight", {
  75447. /**
  75448. * The strength of the bloom.
  75449. */
  75450. get: function () {
  75451. return this._merge.weight;
  75452. },
  75453. set: function (value) {
  75454. this._merge.weight = value;
  75455. },
  75456. enumerable: true,
  75457. configurable: true
  75458. });
  75459. Object.defineProperty(BloomEffect.prototype, "kernel", {
  75460. /**
  75461. * Specifies the size of the bloom blur kernel, relative to the final output size
  75462. */
  75463. get: function () {
  75464. return this._blurX.kernel / this.bloomScale;
  75465. },
  75466. set: function (value) {
  75467. this._blurX.kernel = value * this.bloomScale;
  75468. this._blurY.kernel = value * this.bloomScale;
  75469. },
  75470. enumerable: true,
  75471. configurable: true
  75472. });
  75473. /**
  75474. * Disposes each of the internal effects for a given camera.
  75475. * @param camera The camera to dispose the effect on.
  75476. */
  75477. BloomEffect.prototype.disposeEffects = function (camera) {
  75478. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75479. this._effects[effectIndex].dispose(camera);
  75480. }
  75481. };
  75482. /**
  75483. * Internal
  75484. */
  75485. BloomEffect.prototype._updateEffects = function () {
  75486. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75487. this._effects[effectIndex].updateEffect();
  75488. }
  75489. };
  75490. /**
  75491. * Internal
  75492. * @returns if all the contained post processes are ready.
  75493. */
  75494. BloomEffect.prototype._isReady = function () {
  75495. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75496. if (!this._effects[effectIndex].isReady()) {
  75497. return false;
  75498. }
  75499. }
  75500. return true;
  75501. };
  75502. return BloomEffect;
  75503. }(BABYLON.PostProcessRenderEffect));
  75504. BABYLON.BloomEffect = BloomEffect;
  75505. })(BABYLON || (BABYLON = {}));
  75506. //# sourceMappingURL=babylon.bloomEffect.js.map
  75507. var BABYLON;
  75508. (function (BABYLON) {
  75509. /**
  75510. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  75511. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  75512. */
  75513. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  75514. __extends(DefaultRenderingPipeline, _super);
  75515. /**
  75516. * @constructor
  75517. * @param {string} name - The rendering pipeline name
  75518. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  75519. * @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)
  75520. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  75521. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  75522. */
  75523. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  75524. if (automaticBuild === void 0) { automaticBuild = true; }
  75525. var _this = _super.call(this, scene.getEngine(), name) || this;
  75526. _this._originalCameras = [];
  75527. /**
  75528. * ID of the sharpen post process,
  75529. */
  75530. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  75531. /**
  75532. * ID of the image processing post process;
  75533. */
  75534. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  75535. /**
  75536. * ID of the Fast Approximate Anti-Aliasing post process;
  75537. */
  75538. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  75539. /**
  75540. * ID of the chromatic aberration post process,
  75541. */
  75542. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  75543. /**
  75544. * ID of the grain post process
  75545. */
  75546. _this.GrainPostProcessId = "GrainPostProcessEffect";
  75547. /**
  75548. * Animations which can be used to tweak settings over a period of time
  75549. */
  75550. _this.animations = [];
  75551. _this._imageProcessingConfigurationObserver = null;
  75552. // Values
  75553. _this._sharpenEnabled = false;
  75554. _this._bloomEnabled = false;
  75555. _this._depthOfFieldEnabled = false;
  75556. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  75557. _this._fxaaEnabled = false;
  75558. _this._imageProcessingEnabled = true;
  75559. _this._bloomScale = 0.5;
  75560. _this._chromaticAberrationEnabled = false;
  75561. _this._grainEnabled = false;
  75562. _this._buildAllowed = true;
  75563. _this._resizeObserver = null;
  75564. _this._hardwareScaleLevel = 1.0;
  75565. _this._bloomKernel = 64;
  75566. /**
  75567. * Specifies the weight of the bloom in the final rendering
  75568. */
  75569. _this._bloomWeight = 0.15;
  75570. /**
  75571. * Specifies the luma threshold for the area that will be blurred by the bloom
  75572. */
  75573. _this._bloomThreshold = 0.9;
  75574. _this._samples = 1;
  75575. _this._hasCleared = false;
  75576. _this._prevPostProcess = null;
  75577. _this._prevPrevPostProcess = null;
  75578. _this._cameras = cameras || [];
  75579. _this._originalCameras = _this._cameras.slice();
  75580. _this._buildAllowed = automaticBuild;
  75581. // Initialize
  75582. _this._scene = scene;
  75583. var caps = _this._scene.getEngine().getCaps();
  75584. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  75585. // Misc
  75586. if (_this._hdr) {
  75587. if (caps.textureHalfFloatRender) {
  75588. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  75589. }
  75590. else if (caps.textureFloatRender) {
  75591. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  75592. }
  75593. }
  75594. else {
  75595. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  75596. }
  75597. // Attach
  75598. scene.postProcessRenderPipelineManager.addPipeline(_this);
  75599. var engine = _this._scene.getEngine();
  75600. // Create post processes before hand so they can be modified before enabled.
  75601. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  75602. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  75603. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  75604. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  75605. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  75606. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  75607. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  75608. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  75609. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  75610. _this._resizeObserver = engine.onResizeObservable.add(function () {
  75611. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  75612. _this.bloomKernel = _this.bloomKernel;
  75613. });
  75614. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  75615. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  75616. });
  75617. _this._buildPipeline();
  75618. return _this;
  75619. }
  75620. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  75621. get: function () {
  75622. return this._sharpenEnabled;
  75623. },
  75624. /**
  75625. * Enable or disable the sharpen process from the pipeline
  75626. */
  75627. set: function (enabled) {
  75628. if (this._sharpenEnabled === enabled) {
  75629. return;
  75630. }
  75631. this._sharpenEnabled = enabled;
  75632. this._buildPipeline();
  75633. },
  75634. enumerable: true,
  75635. configurable: true
  75636. });
  75637. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  75638. /**
  75639. * Specifies the size of the bloom blur kernel, relative to the final output size
  75640. */
  75641. get: function () {
  75642. return this._bloomKernel;
  75643. },
  75644. set: function (value) {
  75645. this._bloomKernel = value;
  75646. this.bloom.kernel = value / this._hardwareScaleLevel;
  75647. },
  75648. enumerable: true,
  75649. configurable: true
  75650. });
  75651. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  75652. get: function () {
  75653. return this._bloomWeight;
  75654. },
  75655. /**
  75656. * The strength of the bloom.
  75657. */
  75658. set: function (value) {
  75659. if (this._bloomWeight === value) {
  75660. return;
  75661. }
  75662. this.bloom.weight = value;
  75663. this._bloomWeight = value;
  75664. },
  75665. enumerable: true,
  75666. configurable: true
  75667. });
  75668. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  75669. get: function () {
  75670. return this._bloomThreshold;
  75671. },
  75672. /**
  75673. * The strength of the bloom.
  75674. */
  75675. set: function (value) {
  75676. if (this._bloomThreshold === value) {
  75677. return;
  75678. }
  75679. this.bloom.threshold = value;
  75680. this._bloomThreshold = value;
  75681. },
  75682. enumerable: true,
  75683. configurable: true
  75684. });
  75685. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  75686. get: function () {
  75687. return this._bloomScale;
  75688. },
  75689. /**
  75690. * The scale of the bloom, lower value will provide better performance.
  75691. */
  75692. set: function (value) {
  75693. if (this._bloomScale === value) {
  75694. return;
  75695. }
  75696. this._bloomScale = value;
  75697. // recreate bloom and dispose old as this setting is not dynamic
  75698. this._rebuildBloom();
  75699. this._buildPipeline();
  75700. },
  75701. enumerable: true,
  75702. configurable: true
  75703. });
  75704. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  75705. get: function () {
  75706. return this._bloomEnabled;
  75707. },
  75708. /**
  75709. * Enable or disable the bloom from the pipeline
  75710. */
  75711. set: function (enabled) {
  75712. if (this._bloomEnabled === enabled) {
  75713. return;
  75714. }
  75715. this._bloomEnabled = enabled;
  75716. this._buildPipeline();
  75717. },
  75718. enumerable: true,
  75719. configurable: true
  75720. });
  75721. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  75722. // recreate bloom and dispose old as this setting is not dynamic
  75723. var oldBloom = this.bloom;
  75724. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  75725. this.bloom.threshold = oldBloom.threshold;
  75726. for (var i = 0; i < this._cameras.length; i++) {
  75727. oldBloom.disposeEffects(this._cameras[i]);
  75728. }
  75729. };
  75730. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  75731. /**
  75732. * If the depth of field is enabled.
  75733. */
  75734. get: function () {
  75735. return this._depthOfFieldEnabled;
  75736. },
  75737. set: function (enabled) {
  75738. if (this._depthOfFieldEnabled === enabled) {
  75739. return;
  75740. }
  75741. this._depthOfFieldEnabled = enabled;
  75742. this._buildPipeline();
  75743. },
  75744. enumerable: true,
  75745. configurable: true
  75746. });
  75747. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  75748. /**
  75749. * Blur level of the depth of field effect. (Higher blur will effect performance)
  75750. */
  75751. get: function () {
  75752. return this._depthOfFieldBlurLevel;
  75753. },
  75754. set: function (value) {
  75755. if (this._depthOfFieldBlurLevel === value) {
  75756. return;
  75757. }
  75758. this._depthOfFieldBlurLevel = value;
  75759. // recreate dof and dispose old as this setting is not dynamic
  75760. var oldDof = this.depthOfField;
  75761. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  75762. this.depthOfField.focalLength = oldDof.focalLength;
  75763. this.depthOfField.focusDistance = oldDof.focusDistance;
  75764. this.depthOfField.fStop = oldDof.fStop;
  75765. this.depthOfField.lensSize = oldDof.lensSize;
  75766. for (var i = 0; i < this._cameras.length; i++) {
  75767. oldDof.disposeEffects(this._cameras[i]);
  75768. }
  75769. this._buildPipeline();
  75770. },
  75771. enumerable: true,
  75772. configurable: true
  75773. });
  75774. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  75775. get: function () {
  75776. return this._fxaaEnabled;
  75777. },
  75778. /**
  75779. * If the anti aliasing is enabled.
  75780. */
  75781. set: function (enabled) {
  75782. if (this._fxaaEnabled === enabled) {
  75783. return;
  75784. }
  75785. this._fxaaEnabled = enabled;
  75786. this._buildPipeline();
  75787. },
  75788. enumerable: true,
  75789. configurable: true
  75790. });
  75791. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  75792. get: function () {
  75793. return this._samples;
  75794. },
  75795. /**
  75796. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  75797. */
  75798. set: function (sampleCount) {
  75799. if (this._samples === sampleCount) {
  75800. return;
  75801. }
  75802. this._samples = sampleCount;
  75803. this._buildPipeline();
  75804. },
  75805. enumerable: true,
  75806. configurable: true
  75807. });
  75808. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  75809. get: function () {
  75810. return this._imageProcessingEnabled;
  75811. },
  75812. /**
  75813. * If image processing is enabled.
  75814. */
  75815. set: function (enabled) {
  75816. if (this._imageProcessingEnabled === enabled) {
  75817. return;
  75818. }
  75819. this._imageProcessingEnabled = enabled;
  75820. this._buildPipeline();
  75821. },
  75822. enumerable: true,
  75823. configurable: true
  75824. });
  75825. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  75826. get: function () {
  75827. return this._chromaticAberrationEnabled;
  75828. },
  75829. /**
  75830. * Enable or disable the chromaticAberration process from the pipeline
  75831. */
  75832. set: function (enabled) {
  75833. if (this._chromaticAberrationEnabled === enabled) {
  75834. return;
  75835. }
  75836. this._chromaticAberrationEnabled = enabled;
  75837. this._buildPipeline();
  75838. },
  75839. enumerable: true,
  75840. configurable: true
  75841. });
  75842. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  75843. get: function () {
  75844. return this._grainEnabled;
  75845. },
  75846. /**
  75847. * Enable or disable the grain process from the pipeline
  75848. */
  75849. set: function (enabled) {
  75850. if (this._grainEnabled === enabled) {
  75851. return;
  75852. }
  75853. this._grainEnabled = enabled;
  75854. this._buildPipeline();
  75855. },
  75856. enumerable: true,
  75857. configurable: true
  75858. });
  75859. /**
  75860. * Force the compilation of the entire pipeline.
  75861. */
  75862. DefaultRenderingPipeline.prototype.prepare = function () {
  75863. var previousState = this._buildAllowed;
  75864. this._buildAllowed = true;
  75865. this._buildPipeline();
  75866. this._buildAllowed = previousState;
  75867. };
  75868. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  75869. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  75870. if (this._hasCleared) {
  75871. postProcess.autoClear = false;
  75872. }
  75873. else {
  75874. postProcess.autoClear = true;
  75875. this._scene.autoClear = false;
  75876. this._hasCleared = true;
  75877. }
  75878. if (!skipTextureSharing) {
  75879. if (this._prevPrevPostProcess) {
  75880. postProcess.shareOutputWith(this._prevPrevPostProcess);
  75881. }
  75882. else {
  75883. postProcess.useOwnOutput();
  75884. }
  75885. if (this._prevPostProcess) {
  75886. this._prevPrevPostProcess = this._prevPostProcess;
  75887. }
  75888. this._prevPostProcess = postProcess;
  75889. }
  75890. };
  75891. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  75892. var _this = this;
  75893. if (!this._buildAllowed) {
  75894. return;
  75895. }
  75896. this._scene.autoClear = true;
  75897. var engine = this._scene.getEngine();
  75898. this._disposePostProcesses();
  75899. if (this._cameras !== null) {
  75900. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  75901. // get back cameras to be used to reattach pipeline
  75902. this._cameras = this._originalCameras.slice();
  75903. }
  75904. this._reset();
  75905. this._prevPostProcess = null;
  75906. this._prevPrevPostProcess = null;
  75907. this._hasCleared = false;
  75908. if (this.depthOfFieldEnabled) {
  75909. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  75910. this.depthOfField.depthTexture = depthTexture;
  75911. if (!this.depthOfField._isReady()) {
  75912. this.depthOfField._updateEffects();
  75913. }
  75914. this.addEffect(this.depthOfField);
  75915. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  75916. }
  75917. if (this.bloomEnabled) {
  75918. if (!this.bloom._isReady()) {
  75919. this.bloom._updateEffects();
  75920. }
  75921. this.addEffect(this.bloom);
  75922. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  75923. }
  75924. if (this._imageProcessingEnabled) {
  75925. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  75926. if (this._hdr) {
  75927. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  75928. this._setAutoClearAndTextureSharing(this.imageProcessing);
  75929. }
  75930. else {
  75931. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  75932. }
  75933. }
  75934. if (this.sharpenEnabled) {
  75935. if (!this.sharpen.isReady()) {
  75936. this.sharpen.updateEffect();
  75937. }
  75938. this.addEffect(this._sharpenEffect);
  75939. this._setAutoClearAndTextureSharing(this.sharpen);
  75940. }
  75941. if (this.grainEnabled) {
  75942. if (!this.grain.isReady()) {
  75943. this.grain.updateEffect();
  75944. }
  75945. this.addEffect(this._grainEffect);
  75946. this._setAutoClearAndTextureSharing(this.grain);
  75947. }
  75948. if (this.chromaticAberrationEnabled) {
  75949. if (!this.chromaticAberration.isReady()) {
  75950. this.chromaticAberration.updateEffect();
  75951. }
  75952. this.addEffect(this._chromaticAberrationEffect);
  75953. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  75954. }
  75955. if (this.fxaaEnabled) {
  75956. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  75957. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  75958. this._setAutoClearAndTextureSharing(this.fxaa, true);
  75959. }
  75960. if (this._cameras !== null) {
  75961. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  75962. }
  75963. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  75964. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  75965. }
  75966. };
  75967. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  75968. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  75969. for (var i = 0; i < this._cameras.length; i++) {
  75970. var camera = this._cameras[i];
  75971. if (this.imageProcessing) {
  75972. this.imageProcessing.dispose(camera);
  75973. }
  75974. if (this.fxaa) {
  75975. this.fxaa.dispose(camera);
  75976. }
  75977. // These are created in the constructor and should not be disposed on every pipeline change
  75978. if (disposeNonRecreated) {
  75979. if (this.sharpen) {
  75980. this.sharpen.dispose(camera);
  75981. }
  75982. if (this.depthOfField) {
  75983. this.depthOfField.disposeEffects(camera);
  75984. }
  75985. if (this.bloom) {
  75986. this.bloom.disposeEffects(camera);
  75987. }
  75988. if (this.chromaticAberration) {
  75989. this.chromaticAberration.dispose(camera);
  75990. }
  75991. if (this.grain) {
  75992. this.grain.dispose(camera);
  75993. }
  75994. }
  75995. }
  75996. this.imageProcessing = null;
  75997. this.fxaa = null;
  75998. if (disposeNonRecreated) {
  75999. this.sharpen = null;
  76000. this._sharpenEffect = null;
  76001. this.depthOfField = null;
  76002. this.bloom = null;
  76003. this.chromaticAberration = null;
  76004. this._chromaticAberrationEffect = null;
  76005. this.grain = null;
  76006. this._grainEffect = null;
  76007. }
  76008. };
  76009. /**
  76010. * Dispose of the pipeline and stop all post processes
  76011. */
  76012. DefaultRenderingPipeline.prototype.dispose = function () {
  76013. this._disposePostProcesses(true);
  76014. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  76015. this._scene.autoClear = true;
  76016. if (this._resizeObserver) {
  76017. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  76018. this._resizeObserver = null;
  76019. }
  76020. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  76021. _super.prototype.dispose.call(this);
  76022. };
  76023. /**
  76024. * Serialize the rendering pipeline (Used when exporting)
  76025. * @returns the serialized object
  76026. */
  76027. DefaultRenderingPipeline.prototype.serialize = function () {
  76028. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  76029. serializationObject.customType = "DefaultRenderingPipeline";
  76030. return serializationObject;
  76031. };
  76032. /**
  76033. * Parse the serialized pipeline
  76034. * @param source Source pipeline.
  76035. * @param scene The scene to load the pipeline to.
  76036. * @param rootUrl The URL of the serialized pipeline.
  76037. * @returns An instantiated pipeline from the serialized object.
  76038. */
  76039. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  76040. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  76041. };
  76042. __decorate([
  76043. BABYLON.serialize()
  76044. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  76045. __decorate([
  76046. BABYLON.serialize()
  76047. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  76048. __decorate([
  76049. BABYLON.serialize()
  76050. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  76051. __decorate([
  76052. BABYLON.serialize()
  76053. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  76054. __decorate([
  76055. BABYLON.serialize()
  76056. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  76057. __decorate([
  76058. BABYLON.serialize()
  76059. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  76060. __decorate([
  76061. BABYLON.serialize()
  76062. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  76063. __decorate([
  76064. BABYLON.serialize()
  76065. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  76066. __decorate([
  76067. BABYLON.serialize()
  76068. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  76069. __decorate([
  76070. BABYLON.serialize()
  76071. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  76072. __decorate([
  76073. BABYLON.serialize()
  76074. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  76075. __decorate([
  76076. BABYLON.serialize()
  76077. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  76078. __decorate([
  76079. BABYLON.serialize()
  76080. ], DefaultRenderingPipeline.prototype, "samples", null);
  76081. __decorate([
  76082. BABYLON.serialize()
  76083. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  76084. __decorate([
  76085. BABYLON.serialize()
  76086. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  76087. __decorate([
  76088. BABYLON.serialize()
  76089. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  76090. return DefaultRenderingPipeline;
  76091. }(BABYLON.PostProcessRenderPipeline));
  76092. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  76093. })(BABYLON || (BABYLON = {}));
  76094. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  76095. var BABYLON;
  76096. (function (BABYLON) {
  76097. /**
  76098. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  76099. */
  76100. var GeometryBufferRenderer = /** @class */ (function () {
  76101. /**
  76102. * Creates a new G Buffer for the scene
  76103. * @param scene The scene the buffer belongs to
  76104. * @param ratio How big is the buffer related to the main canvas.
  76105. */
  76106. function GeometryBufferRenderer(scene, ratio) {
  76107. if (ratio === void 0) { ratio = 1; }
  76108. this._enablePosition = false;
  76109. this._scene = scene;
  76110. this._ratio = ratio;
  76111. // Render target
  76112. this._createRenderTargets();
  76113. }
  76114. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  76115. /**
  76116. * Set the render list (meshes to be rendered) used in the G buffer.
  76117. */
  76118. set: function (meshes) {
  76119. this._multiRenderTarget.renderList = meshes;
  76120. },
  76121. enumerable: true,
  76122. configurable: true
  76123. });
  76124. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  76125. /**
  76126. * Gets wether or not G buffer are supported by the running hardware.
  76127. * This requires draw buffer supports
  76128. */
  76129. get: function () {
  76130. return this._multiRenderTarget.isSupported;
  76131. },
  76132. enumerable: true,
  76133. configurable: true
  76134. });
  76135. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  76136. /**
  76137. * Gets wether or not position are enabled for the G buffer.
  76138. */
  76139. get: function () {
  76140. return this._enablePosition;
  76141. },
  76142. /**
  76143. * Sets wether or not position are enabled for the G buffer.
  76144. */
  76145. set: function (enable) {
  76146. this._enablePosition = enable;
  76147. this.dispose();
  76148. this._createRenderTargets();
  76149. },
  76150. enumerable: true,
  76151. configurable: true
  76152. });
  76153. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  76154. /**
  76155. * Gets the scene associated with the buffer.
  76156. */
  76157. get: function () {
  76158. return this._scene;
  76159. },
  76160. enumerable: true,
  76161. configurable: true
  76162. });
  76163. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  76164. /**
  76165. * Gets the ratio used by the buffer during its creation.
  76166. * How big is the buffer related to the main canvas.
  76167. */
  76168. get: function () {
  76169. return this._ratio;
  76170. },
  76171. enumerable: true,
  76172. configurable: true
  76173. });
  76174. /**
  76175. * Checks wether everything is ready to render a submesh to the G buffer.
  76176. * @param subMesh the submesh to check readiness for
  76177. * @param useInstances is the mesh drawn using instance or not
  76178. * @returns true if ready otherwise false
  76179. */
  76180. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  76181. var material = subMesh.getMaterial();
  76182. if (material && material.disableDepthWrite) {
  76183. return false;
  76184. }
  76185. var defines = [];
  76186. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  76187. var mesh = subMesh.getMesh();
  76188. // Alpha test
  76189. if (material && material.needAlphaTesting()) {
  76190. defines.push("#define ALPHATEST");
  76191. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76192. attribs.push(BABYLON.VertexBuffer.UVKind);
  76193. defines.push("#define UV1");
  76194. }
  76195. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  76196. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76197. defines.push("#define UV2");
  76198. }
  76199. }
  76200. // Buffers
  76201. if (this._enablePosition) {
  76202. defines.push("#define POSITION");
  76203. }
  76204. // Bones
  76205. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  76206. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76207. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76208. if (mesh.numBoneInfluencers > 4) {
  76209. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  76210. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  76211. }
  76212. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  76213. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  76214. }
  76215. else {
  76216. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76217. }
  76218. // Instances
  76219. if (useInstances) {
  76220. defines.push("#define INSTANCES");
  76221. attribs.push("world0");
  76222. attribs.push("world1");
  76223. attribs.push("world2");
  76224. attribs.push("world3");
  76225. }
  76226. // Get correct effect
  76227. var join = defines.join("\n");
  76228. if (this._cachedDefines !== join) {
  76229. this._cachedDefines = join;
  76230. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  76231. }
  76232. return this._effect.isReady();
  76233. };
  76234. /**
  76235. * Gets the current underlying G Buffer.
  76236. * @returns the buffer
  76237. */
  76238. GeometryBufferRenderer.prototype.getGBuffer = function () {
  76239. return this._multiRenderTarget;
  76240. };
  76241. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  76242. /**
  76243. * Gets the number of samples used to render the buffer (anti aliasing).
  76244. */
  76245. get: function () {
  76246. return this._multiRenderTarget.samples;
  76247. },
  76248. /**
  76249. * Sets the number of samples used to render the buffer (anti aliasing).
  76250. */
  76251. set: function (value) {
  76252. this._multiRenderTarget.samples = value;
  76253. },
  76254. enumerable: true,
  76255. configurable: true
  76256. });
  76257. /**
  76258. * Disposes the renderer and frees up associated resources.
  76259. */
  76260. GeometryBufferRenderer.prototype.dispose = function () {
  76261. this.getGBuffer().dispose();
  76262. };
  76263. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  76264. var _this = this;
  76265. var engine = this._scene.getEngine();
  76266. var count = this._enablePosition ? 3 : 2;
  76267. 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 });
  76268. if (!this.isSupported) {
  76269. return;
  76270. }
  76271. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76272. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76273. this._multiRenderTarget.refreshRate = 1;
  76274. this._multiRenderTarget.renderParticles = false;
  76275. this._multiRenderTarget.renderList = null;
  76276. // set default depth value to 1.0 (far away)
  76277. this._multiRenderTarget.onClearObservable.add(function (engine) {
  76278. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  76279. });
  76280. // Custom render function
  76281. var renderSubMesh = function (subMesh) {
  76282. var mesh = subMesh.getRenderingMesh();
  76283. var scene = _this._scene;
  76284. var engine = scene.getEngine();
  76285. var material = subMesh.getMaterial();
  76286. if (!material) {
  76287. return;
  76288. }
  76289. // Culling
  76290. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  76291. // Managing instances
  76292. var batch = mesh._getInstancesRenderList(subMesh._id);
  76293. if (batch.mustReturn) {
  76294. return;
  76295. }
  76296. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  76297. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  76298. engine.enableEffect(_this._effect);
  76299. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  76300. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  76301. _this._effect.setMatrix("view", scene.getViewMatrix());
  76302. // Alpha test
  76303. if (material && material.needAlphaTesting()) {
  76304. var alphaTexture = material.getAlphaTestTexture();
  76305. if (alphaTexture) {
  76306. _this._effect.setTexture("diffuseSampler", alphaTexture);
  76307. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  76308. }
  76309. }
  76310. // Bones
  76311. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76312. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  76313. }
  76314. // Draw
  76315. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  76316. }
  76317. };
  76318. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  76319. var index;
  76320. if (depthOnlySubMeshes.length) {
  76321. engine.setColorWrite(false);
  76322. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  76323. renderSubMesh(depthOnlySubMeshes.data[index]);
  76324. }
  76325. engine.setColorWrite(true);
  76326. }
  76327. for (index = 0; index < opaqueSubMeshes.length; index++) {
  76328. renderSubMesh(opaqueSubMeshes.data[index]);
  76329. }
  76330. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  76331. renderSubMesh(alphaTestSubMeshes.data[index]);
  76332. }
  76333. };
  76334. };
  76335. return GeometryBufferRenderer;
  76336. }());
  76337. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  76338. })(BABYLON || (BABYLON = {}));
  76339. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  76340. var BABYLON;
  76341. (function (BABYLON) {
  76342. var RefractionPostProcess = /** @class */ (function (_super) {
  76343. __extends(RefractionPostProcess, _super);
  76344. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  76345. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  76346. _this.color = color;
  76347. _this.depth = depth;
  76348. _this.colorLevel = colorLevel;
  76349. _this._ownRefractionTexture = true;
  76350. _this.onActivateObservable.add(function (cam) {
  76351. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  76352. });
  76353. _this.onApplyObservable.add(function (effect) {
  76354. effect.setColor3("baseColor", _this.color);
  76355. effect.setFloat("depth", _this.depth);
  76356. effect.setFloat("colorLevel", _this.colorLevel);
  76357. effect.setTexture("refractionSampler", _this._refTexture);
  76358. });
  76359. return _this;
  76360. }
  76361. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  76362. /**
  76363. * Gets or sets the refraction texture
  76364. * Please note that you are responsible for disposing the texture if you set it manually
  76365. */
  76366. get: function () {
  76367. return this._refTexture;
  76368. },
  76369. set: function (value) {
  76370. if (this._refTexture && this._ownRefractionTexture) {
  76371. this._refTexture.dispose();
  76372. }
  76373. this._refTexture = value;
  76374. this._ownRefractionTexture = false;
  76375. },
  76376. enumerable: true,
  76377. configurable: true
  76378. });
  76379. // Methods
  76380. RefractionPostProcess.prototype.dispose = function (camera) {
  76381. if (this._refTexture && this._ownRefractionTexture) {
  76382. this._refTexture.dispose();
  76383. this._refTexture = null;
  76384. }
  76385. _super.prototype.dispose.call(this, camera);
  76386. };
  76387. return RefractionPostProcess;
  76388. }(BABYLON.PostProcess));
  76389. BABYLON.RefractionPostProcess = RefractionPostProcess;
  76390. })(BABYLON || (BABYLON = {}));
  76391. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  76392. var BABYLON;
  76393. (function (BABYLON) {
  76394. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  76395. __extends(BlackAndWhitePostProcess, _super);
  76396. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  76397. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  76398. _this.degree = 1;
  76399. _this.onApplyObservable.add(function (effect) {
  76400. effect.setFloat("degree", _this.degree);
  76401. });
  76402. return _this;
  76403. }
  76404. return BlackAndWhitePostProcess;
  76405. }(BABYLON.PostProcess));
  76406. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  76407. })(BABYLON || (BABYLON = {}));
  76408. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  76409. var BABYLON;
  76410. (function (BABYLON) {
  76411. /**
  76412. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  76413. * input texture to perform effects such as edge detection or sharpening
  76414. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  76415. */
  76416. var ConvolutionPostProcess = /** @class */ (function (_super) {
  76417. __extends(ConvolutionPostProcess, _super);
  76418. /**
  76419. * Creates a new instance ConvolutionPostProcess
  76420. * @param name The name of the effect.
  76421. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  76422. * @param options The required width/height ratio to downsize to before computing the render pass.
  76423. * @param camera The camera to apply the render pass to.
  76424. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76425. * @param engine The engine which the post process will be applied. (default: current engine)
  76426. * @param reusable If the post process can be reused on the same frame. (default: false)
  76427. * @param textureType Type of textures used when performing the post process. (default: 0)
  76428. */
  76429. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  76430. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76431. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  76432. _this.kernel = kernel;
  76433. _this.onApply = function (effect) {
  76434. effect.setFloat2("screenSize", _this.width, _this.height);
  76435. effect.setArray("kernel", _this.kernel);
  76436. };
  76437. return _this;
  76438. }
  76439. // Statics
  76440. /**
  76441. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76442. */
  76443. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  76444. /**
  76445. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76446. */
  76447. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  76448. /**
  76449. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76450. */
  76451. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  76452. /**
  76453. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76454. */
  76455. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  76456. /**
  76457. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76458. */
  76459. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  76460. /**
  76461. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76462. */
  76463. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  76464. return ConvolutionPostProcess;
  76465. }(BABYLON.PostProcess));
  76466. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  76467. })(BABYLON || (BABYLON = {}));
  76468. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  76469. var BABYLON;
  76470. (function (BABYLON) {
  76471. var FilterPostProcess = /** @class */ (function (_super) {
  76472. __extends(FilterPostProcess, _super);
  76473. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  76474. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  76475. _this.kernelMatrix = kernelMatrix;
  76476. _this.onApply = function (effect) {
  76477. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  76478. };
  76479. return _this;
  76480. }
  76481. return FilterPostProcess;
  76482. }(BABYLON.PostProcess));
  76483. BABYLON.FilterPostProcess = FilterPostProcess;
  76484. })(BABYLON || (BABYLON = {}));
  76485. //# sourceMappingURL=babylon.filterPostProcess.js.map
  76486. var BABYLON;
  76487. (function (BABYLON) {
  76488. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  76489. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  76490. __extends(VolumetricLightScatteringPostProcess, _super);
  76491. /**
  76492. * @constructor
  76493. * @param {string} name - The post-process name
  76494. * @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)
  76495. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  76496. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  76497. * @param {number} samples - The post-process quality, default 100
  76498. * @param {number} samplingMode - The post-process filtering mode
  76499. * @param {BABYLON.Engine} engine - The babylon engine
  76500. * @param {boolean} reusable - If the post-process is reusable
  76501. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  76502. */
  76503. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  76504. if (samples === void 0) { samples = 100; }
  76505. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  76506. 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;
  76507. _this._screenCoordinates = BABYLON.Vector2.Zero();
  76508. /**
  76509. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  76510. */
  76511. _this.customMeshPosition = BABYLON.Vector3.Zero();
  76512. /**
  76513. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  76514. */
  76515. _this.useCustomMeshPosition = false;
  76516. /**
  76517. * If the post-process should inverse the light scattering direction
  76518. */
  76519. _this.invert = true;
  76520. /**
  76521. * Array containing the excluded meshes not rendered in the internal pass
  76522. */
  76523. _this.excludedMeshes = new Array();
  76524. /**
  76525. * Controls the overall intensity of the post-process
  76526. */
  76527. _this.exposure = 0.3;
  76528. /**
  76529. * Dissipates each sample's contribution in range [0, 1]
  76530. */
  76531. _this.decay = 0.96815;
  76532. /**
  76533. * Controls the overall intensity of each sample
  76534. */
  76535. _this.weight = 0.58767;
  76536. /**
  76537. * Controls the density of each sample
  76538. */
  76539. _this.density = 0.926;
  76540. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  76541. engine = scene.getEngine();
  76542. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  76543. // Configure mesh
  76544. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  76545. // Configure
  76546. _this._createPass(scene, ratio.passRatio || ratio);
  76547. _this.onActivate = function (camera) {
  76548. if (!_this.isSupported) {
  76549. _this.dispose(camera);
  76550. }
  76551. _this.onActivate = null;
  76552. };
  76553. _this.onApplyObservable.add(function (effect) {
  76554. _this._updateMeshScreenCoordinates(scene);
  76555. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  76556. effect.setFloat("exposure", _this.exposure);
  76557. effect.setFloat("decay", _this.decay);
  76558. effect.setFloat("weight", _this.weight);
  76559. effect.setFloat("density", _this.density);
  76560. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  76561. });
  76562. return _this;
  76563. }
  76564. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  76565. get: function () {
  76566. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  76567. return false;
  76568. },
  76569. set: function (useDiffuseColor) {
  76570. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  76571. },
  76572. enumerable: true,
  76573. configurable: true
  76574. });
  76575. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  76576. return "VolumetricLightScatteringPostProcess";
  76577. };
  76578. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  76579. var mesh = subMesh.getMesh();
  76580. // Render this.mesh as default
  76581. if (mesh === this.mesh && mesh.material) {
  76582. return mesh.material.isReady(mesh);
  76583. }
  76584. var defines = [];
  76585. var attribs = [BABYLON.VertexBuffer.PositionKind];
  76586. var material = subMesh.getMaterial();
  76587. // Alpha test
  76588. if (material) {
  76589. if (material.needAlphaTesting()) {
  76590. defines.push("#define ALPHATEST");
  76591. }
  76592. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76593. attribs.push(BABYLON.VertexBuffer.UVKind);
  76594. defines.push("#define UV1");
  76595. }
  76596. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  76597. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76598. defines.push("#define UV2");
  76599. }
  76600. }
  76601. // Bones
  76602. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  76603. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76604. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76605. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  76606. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  76607. }
  76608. else {
  76609. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76610. }
  76611. // Instances
  76612. if (useInstances) {
  76613. defines.push("#define INSTANCES");
  76614. attribs.push("world0");
  76615. attribs.push("world1");
  76616. attribs.push("world2");
  76617. attribs.push("world3");
  76618. }
  76619. // Get correct effect
  76620. var join = defines.join("\n");
  76621. if (this._cachedDefines !== join) {
  76622. this._cachedDefines = join;
  76623. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  76624. }
  76625. return this._volumetricLightScatteringPass.isReady();
  76626. };
  76627. /**
  76628. * Sets the new light position for light scattering effect
  76629. * @param {BABYLON.Vector3} The new custom light position
  76630. */
  76631. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  76632. this.customMeshPosition = position;
  76633. };
  76634. /**
  76635. * Returns the light position for light scattering effect
  76636. * @return {BABYLON.Vector3} The custom light position
  76637. */
  76638. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  76639. return this.customMeshPosition;
  76640. };
  76641. /**
  76642. * Disposes the internal assets and detaches the post-process from the camera
  76643. */
  76644. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  76645. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  76646. if (rttIndex !== -1) {
  76647. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  76648. }
  76649. this._volumetricLightScatteringRTT.dispose();
  76650. _super.prototype.dispose.call(this, camera);
  76651. };
  76652. /**
  76653. * Returns the render target texture used by the post-process
  76654. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  76655. */
  76656. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  76657. return this._volumetricLightScatteringRTT;
  76658. };
  76659. // Private methods
  76660. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  76661. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  76662. return true;
  76663. }
  76664. return false;
  76665. };
  76666. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  76667. var _this = this;
  76668. var engine = scene.getEngine();
  76669. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  76670. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76671. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76672. this._volumetricLightScatteringRTT.renderList = null;
  76673. this._volumetricLightScatteringRTT.renderParticles = false;
  76674. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  76675. var camera = this.getCamera();
  76676. if (camera) {
  76677. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  76678. }
  76679. else {
  76680. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  76681. }
  76682. // Custom render function for submeshes
  76683. var renderSubMesh = function (subMesh) {
  76684. var mesh = subMesh.getRenderingMesh();
  76685. if (_this._meshExcluded(mesh)) {
  76686. return;
  76687. }
  76688. var material = subMesh.getMaterial();
  76689. if (!material) {
  76690. return;
  76691. }
  76692. var scene = mesh.getScene();
  76693. var engine = scene.getEngine();
  76694. // Culling
  76695. engine.setState(material.backFaceCulling);
  76696. // Managing instances
  76697. var batch = mesh._getInstancesRenderList(subMesh._id);
  76698. if (batch.mustReturn) {
  76699. return;
  76700. }
  76701. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  76702. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  76703. var effect = _this._volumetricLightScatteringPass;
  76704. if (mesh === _this.mesh) {
  76705. if (subMesh.effect) {
  76706. effect = subMesh.effect;
  76707. }
  76708. else {
  76709. effect = material.getEffect();
  76710. }
  76711. }
  76712. engine.enableEffect(effect);
  76713. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  76714. if (mesh === _this.mesh) {
  76715. material.bind(mesh.getWorldMatrix(), mesh);
  76716. }
  76717. else {
  76718. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  76719. // Alpha test
  76720. if (material && material.needAlphaTesting()) {
  76721. var alphaTexture = material.getAlphaTestTexture();
  76722. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  76723. if (alphaTexture) {
  76724. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  76725. }
  76726. }
  76727. // Bones
  76728. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76729. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  76730. }
  76731. }
  76732. // Draw
  76733. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  76734. }
  76735. };
  76736. // Render target texture callbacks
  76737. var savedSceneClearColor;
  76738. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  76739. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  76740. savedSceneClearColor = scene.clearColor;
  76741. scene.clearColor = sceneClearColor;
  76742. });
  76743. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  76744. scene.clearColor = savedSceneClearColor;
  76745. });
  76746. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  76747. var engine = scene.getEngine();
  76748. var index;
  76749. if (depthOnlySubMeshes.length) {
  76750. engine.setColorWrite(false);
  76751. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  76752. renderSubMesh(depthOnlySubMeshes.data[index]);
  76753. }
  76754. engine.setColorWrite(true);
  76755. }
  76756. for (index = 0; index < opaqueSubMeshes.length; index++) {
  76757. renderSubMesh(opaqueSubMeshes.data[index]);
  76758. }
  76759. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  76760. renderSubMesh(alphaTestSubMeshes.data[index]);
  76761. }
  76762. if (transparentSubMeshes.length) {
  76763. // Sort sub meshes
  76764. for (index = 0; index < transparentSubMeshes.length; index++) {
  76765. var submesh = transparentSubMeshes.data[index];
  76766. var boundingInfo = submesh.getBoundingInfo();
  76767. if (boundingInfo && scene.activeCamera) {
  76768. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  76769. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  76770. }
  76771. }
  76772. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  76773. sortedArray.sort(function (a, b) {
  76774. // Alpha index first
  76775. if (a._alphaIndex > b._alphaIndex) {
  76776. return 1;
  76777. }
  76778. if (a._alphaIndex < b._alphaIndex) {
  76779. return -1;
  76780. }
  76781. // Then distance to camera
  76782. if (a._distanceToCamera < b._distanceToCamera) {
  76783. return 1;
  76784. }
  76785. if (a._distanceToCamera > b._distanceToCamera) {
  76786. return -1;
  76787. }
  76788. return 0;
  76789. });
  76790. // Render sub meshes
  76791. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  76792. for (index = 0; index < sortedArray.length; index++) {
  76793. renderSubMesh(sortedArray[index]);
  76794. }
  76795. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  76796. }
  76797. };
  76798. };
  76799. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  76800. var transform = scene.getTransformMatrix();
  76801. var meshPosition;
  76802. if (this.useCustomMeshPosition) {
  76803. meshPosition = this.customMeshPosition;
  76804. }
  76805. else if (this.attachedNode) {
  76806. meshPosition = this.attachedNode.position;
  76807. }
  76808. else {
  76809. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  76810. }
  76811. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  76812. this._screenCoordinates.x = pos.x / this._viewPort.width;
  76813. this._screenCoordinates.y = pos.y / this._viewPort.height;
  76814. if (this.invert)
  76815. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  76816. };
  76817. // Static methods
  76818. /**
  76819. * Creates a default mesh for the Volumeric Light Scattering post-process
  76820. * @param {string} The mesh name
  76821. * @param {BABYLON.Scene} The scene where to create the mesh
  76822. * @return {BABYLON.Mesh} the default mesh
  76823. */
  76824. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  76825. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  76826. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  76827. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  76828. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  76829. mesh.material = material;
  76830. return mesh;
  76831. };
  76832. __decorate([
  76833. BABYLON.serializeAsVector3()
  76834. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  76835. __decorate([
  76836. BABYLON.serialize()
  76837. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  76838. __decorate([
  76839. BABYLON.serialize()
  76840. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  76841. __decorate([
  76842. BABYLON.serializeAsMeshReference()
  76843. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  76844. __decorate([
  76845. BABYLON.serialize()
  76846. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  76847. __decorate([
  76848. BABYLON.serialize()
  76849. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  76850. __decorate([
  76851. BABYLON.serialize()
  76852. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  76853. __decorate([
  76854. BABYLON.serialize()
  76855. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  76856. __decorate([
  76857. BABYLON.serialize()
  76858. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  76859. return VolumetricLightScatteringPostProcess;
  76860. }(BABYLON.PostProcess));
  76861. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  76862. })(BABYLON || (BABYLON = {}));
  76863. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  76864. //
  76865. // This post-process allows the modification of rendered colors by using
  76866. // a 'look-up table' (LUT). This effect is also called Color Grading.
  76867. //
  76868. // The object needs to be provided an url to a texture containing the color
  76869. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  76870. // Use an image editing software to tweak the LUT to match your needs.
  76871. //
  76872. // For an example of a color LUT, see here:
  76873. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  76874. // For explanations on color grading, see here:
  76875. // http://udn.epicgames.com/Three/ColorGrading.html
  76876. //
  76877. var BABYLON;
  76878. (function (BABYLON) {
  76879. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  76880. __extends(ColorCorrectionPostProcess, _super);
  76881. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  76882. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  76883. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  76884. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  76885. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76886. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76887. _this.onApply = function (effect) {
  76888. effect.setTexture("colorTable", _this._colorTableTexture);
  76889. };
  76890. return _this;
  76891. }
  76892. return ColorCorrectionPostProcess;
  76893. }(BABYLON.PostProcess));
  76894. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  76895. })(BABYLON || (BABYLON = {}));
  76896. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  76897. var BABYLON;
  76898. (function (BABYLON) {
  76899. /** Defines operator used for tonemapping */
  76900. var TonemappingOperator;
  76901. (function (TonemappingOperator) {
  76902. /** Hable */
  76903. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  76904. /** Reinhard */
  76905. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  76906. /** HejiDawson */
  76907. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  76908. /** Photographic */
  76909. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  76910. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  76911. ;
  76912. /**
  76913. * Defines a post process to apply tone mapping
  76914. */
  76915. var TonemapPostProcess = /** @class */ (function (_super) {
  76916. __extends(TonemapPostProcess, _super);
  76917. /**
  76918. * Creates a new TonemapPostProcess
  76919. * @param name defines the name of the postprocess
  76920. * @param _operator defines the operator to use
  76921. * @param exposureAdjustment defines the required exposure adjustement
  76922. * @param camera defines the camera to use (can be null)
  76923. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  76924. * @param engine defines the hosting engine (can be ignore if camera is set)
  76925. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  76926. */
  76927. function TonemapPostProcess(name, _operator,
  76928. /** Defines the required exposure adjustement */
  76929. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  76930. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  76931. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76932. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  76933. _this._operator = _operator;
  76934. _this.exposureAdjustment = exposureAdjustment;
  76935. var defines = "#define ";
  76936. if (_this._operator === TonemappingOperator.Hable)
  76937. defines += "HABLE_TONEMAPPING";
  76938. else if (_this._operator === TonemappingOperator.Reinhard)
  76939. defines += "REINHARD_TONEMAPPING";
  76940. else if (_this._operator === TonemappingOperator.HejiDawson)
  76941. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  76942. else if (_this._operator === TonemappingOperator.Photographic)
  76943. defines += "PHOTOGRAPHIC_TONEMAPPING";
  76944. //sadly a second call to create the effect.
  76945. _this.updateEffect(defines);
  76946. _this.onApply = function (effect) {
  76947. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  76948. };
  76949. return _this;
  76950. }
  76951. return TonemapPostProcess;
  76952. }(BABYLON.PostProcess));
  76953. BABYLON.TonemapPostProcess = TonemapPostProcess;
  76954. })(BABYLON || (BABYLON = {}));
  76955. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  76956. var BABYLON;
  76957. (function (BABYLON) {
  76958. var DisplayPassPostProcess = /** @class */ (function (_super) {
  76959. __extends(DisplayPassPostProcess, _super);
  76960. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  76961. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  76962. }
  76963. return DisplayPassPostProcess;
  76964. }(BABYLON.PostProcess));
  76965. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  76966. })(BABYLON || (BABYLON = {}));
  76967. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  76968. var BABYLON;
  76969. (function (BABYLON) {
  76970. var HighlightsPostProcess = /** @class */ (function (_super) {
  76971. __extends(HighlightsPostProcess, _super);
  76972. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  76973. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76974. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  76975. }
  76976. return HighlightsPostProcess;
  76977. }(BABYLON.PostProcess));
  76978. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  76979. })(BABYLON || (BABYLON = {}));
  76980. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  76981. var BABYLON;
  76982. (function (BABYLON) {
  76983. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  76984. __extends(ImageProcessingPostProcess, _super);
  76985. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  76986. if (camera === void 0) { camera = null; }
  76987. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76988. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  76989. _this._fromLinearSpace = true;
  76990. /**
  76991. * Defines cache preventing GC.
  76992. */
  76993. _this._defines = {
  76994. IMAGEPROCESSING: false,
  76995. VIGNETTE: false,
  76996. VIGNETTEBLENDMODEMULTIPLY: false,
  76997. VIGNETTEBLENDMODEOPAQUE: false,
  76998. TONEMAPPING: false,
  76999. CONTRAST: false,
  77000. COLORCURVES: false,
  77001. COLORGRADING: false,
  77002. COLORGRADING3D: false,
  77003. FROMLINEARSPACE: false,
  77004. SAMPLER3DGREENDEPTH: false,
  77005. SAMPLER3DBGRMAP: false,
  77006. IMAGEPROCESSINGPOSTPROCESS: false,
  77007. EXPOSURE: false,
  77008. };
  77009. // Setup the configuration as forced by the constructor. This would then not force the
  77010. // scene materials output in linear space and let untouched the default forward pass.
  77011. if (imageProcessingConfiguration) {
  77012. imageProcessingConfiguration.applyByPostProcess = true;
  77013. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  77014. // This will cause the shader to be compiled
  77015. _this.fromLinearSpace = false;
  77016. }
  77017. // Setup the default processing configuration to the scene.
  77018. else {
  77019. _this._attachImageProcessingConfiguration(null, true);
  77020. _this.imageProcessingConfiguration.applyByPostProcess = true;
  77021. }
  77022. _this.onApply = function (effect) {
  77023. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  77024. };
  77025. return _this;
  77026. }
  77027. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  77028. /**
  77029. * Gets the image processing configuration used either in this material.
  77030. */
  77031. get: function () {
  77032. return this._imageProcessingConfiguration;
  77033. },
  77034. /**
  77035. * Sets the Default image processing configuration used either in the this material.
  77036. *
  77037. * If sets to null, the scene one is in use.
  77038. */
  77039. set: function (value) {
  77040. this._attachImageProcessingConfiguration(value);
  77041. },
  77042. enumerable: true,
  77043. configurable: true
  77044. });
  77045. /**
  77046. * Attaches a new image processing configuration to the PBR Material.
  77047. * @param configuration
  77048. */
  77049. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  77050. var _this = this;
  77051. if (doNotBuild === void 0) { doNotBuild = false; }
  77052. if (configuration === this._imageProcessingConfiguration) {
  77053. return;
  77054. }
  77055. // Detaches observer.
  77056. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  77057. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  77058. }
  77059. // Pick the scene configuration if needed.
  77060. if (!configuration) {
  77061. var scene = null;
  77062. var engine = this.getEngine();
  77063. var camera = this.getCamera();
  77064. if (camera) {
  77065. scene = camera.getScene();
  77066. }
  77067. else if (engine && engine.scenes) {
  77068. var scenes = engine.scenes;
  77069. scene = scenes[scenes.length - 1];
  77070. }
  77071. else {
  77072. scene = BABYLON.Engine.LastCreatedScene;
  77073. }
  77074. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  77075. }
  77076. else {
  77077. this._imageProcessingConfiguration = configuration;
  77078. }
  77079. // Attaches observer.
  77080. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  77081. _this._updateParameters();
  77082. });
  77083. // Ensure the effect will be rebuilt.
  77084. if (!doNotBuild) {
  77085. this._updateParameters();
  77086. }
  77087. };
  77088. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  77089. /**
  77090. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  77091. */
  77092. get: function () {
  77093. return this.imageProcessingConfiguration.colorCurves;
  77094. },
  77095. /**
  77096. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  77097. */
  77098. set: function (value) {
  77099. this.imageProcessingConfiguration.colorCurves = value;
  77100. },
  77101. enumerable: true,
  77102. configurable: true
  77103. });
  77104. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  77105. /**
  77106. * Gets wether the color curves effect is enabled.
  77107. */
  77108. get: function () {
  77109. return this.imageProcessingConfiguration.colorCurvesEnabled;
  77110. },
  77111. /**
  77112. * Sets wether the color curves effect is enabled.
  77113. */
  77114. set: function (value) {
  77115. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  77116. },
  77117. enumerable: true,
  77118. configurable: true
  77119. });
  77120. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  77121. /**
  77122. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  77123. */
  77124. get: function () {
  77125. return this.imageProcessingConfiguration.colorGradingTexture;
  77126. },
  77127. /**
  77128. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  77129. */
  77130. set: function (value) {
  77131. this.imageProcessingConfiguration.colorGradingTexture = value;
  77132. },
  77133. enumerable: true,
  77134. configurable: true
  77135. });
  77136. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  77137. /**
  77138. * Gets wether the color grading effect is enabled.
  77139. */
  77140. get: function () {
  77141. return this.imageProcessingConfiguration.colorGradingEnabled;
  77142. },
  77143. /**
  77144. * Gets wether the color grading effect is enabled.
  77145. */
  77146. set: function (value) {
  77147. this.imageProcessingConfiguration.colorGradingEnabled = value;
  77148. },
  77149. enumerable: true,
  77150. configurable: true
  77151. });
  77152. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  77153. /**
  77154. * Gets exposure used in the effect.
  77155. */
  77156. get: function () {
  77157. return this.imageProcessingConfiguration.exposure;
  77158. },
  77159. /**
  77160. * Sets exposure used in the effect.
  77161. */
  77162. set: function (value) {
  77163. this.imageProcessingConfiguration.exposure = value;
  77164. },
  77165. enumerable: true,
  77166. configurable: true
  77167. });
  77168. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  77169. /**
  77170. * Gets wether tonemapping is enabled or not.
  77171. */
  77172. get: function () {
  77173. return this._imageProcessingConfiguration.toneMappingEnabled;
  77174. },
  77175. /**
  77176. * Sets wether tonemapping is enabled or not
  77177. */
  77178. set: function (value) {
  77179. this._imageProcessingConfiguration.toneMappingEnabled = value;
  77180. },
  77181. enumerable: true,
  77182. configurable: true
  77183. });
  77184. ;
  77185. ;
  77186. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  77187. /**
  77188. * Gets contrast used in the effect.
  77189. */
  77190. get: function () {
  77191. return this.imageProcessingConfiguration.contrast;
  77192. },
  77193. /**
  77194. * Sets contrast used in the effect.
  77195. */
  77196. set: function (value) {
  77197. this.imageProcessingConfiguration.contrast = value;
  77198. },
  77199. enumerable: true,
  77200. configurable: true
  77201. });
  77202. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  77203. /**
  77204. * Gets Vignette stretch size.
  77205. */
  77206. get: function () {
  77207. return this.imageProcessingConfiguration.vignetteStretch;
  77208. },
  77209. /**
  77210. * Sets Vignette stretch size.
  77211. */
  77212. set: function (value) {
  77213. this.imageProcessingConfiguration.vignetteStretch = value;
  77214. },
  77215. enumerable: true,
  77216. configurable: true
  77217. });
  77218. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  77219. /**
  77220. * Gets Vignette centre X Offset.
  77221. */
  77222. get: function () {
  77223. return this.imageProcessingConfiguration.vignetteCentreX;
  77224. },
  77225. /**
  77226. * Sets Vignette centre X Offset.
  77227. */
  77228. set: function (value) {
  77229. this.imageProcessingConfiguration.vignetteCentreX = value;
  77230. },
  77231. enumerable: true,
  77232. configurable: true
  77233. });
  77234. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  77235. /**
  77236. * Gets Vignette centre Y Offset.
  77237. */
  77238. get: function () {
  77239. return this.imageProcessingConfiguration.vignetteCentreY;
  77240. },
  77241. /**
  77242. * Sets Vignette centre Y Offset.
  77243. */
  77244. set: function (value) {
  77245. this.imageProcessingConfiguration.vignetteCentreY = value;
  77246. },
  77247. enumerable: true,
  77248. configurable: true
  77249. });
  77250. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  77251. /**
  77252. * Gets Vignette weight or intensity of the vignette effect.
  77253. */
  77254. get: function () {
  77255. return this.imageProcessingConfiguration.vignetteWeight;
  77256. },
  77257. /**
  77258. * Sets Vignette weight or intensity of the vignette effect.
  77259. */
  77260. set: function (value) {
  77261. this.imageProcessingConfiguration.vignetteWeight = value;
  77262. },
  77263. enumerable: true,
  77264. configurable: true
  77265. });
  77266. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  77267. /**
  77268. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  77269. * if vignetteEnabled is set to true.
  77270. */
  77271. get: function () {
  77272. return this.imageProcessingConfiguration.vignetteColor;
  77273. },
  77274. /**
  77275. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  77276. * if vignetteEnabled is set to true.
  77277. */
  77278. set: function (value) {
  77279. this.imageProcessingConfiguration.vignetteColor = value;
  77280. },
  77281. enumerable: true,
  77282. configurable: true
  77283. });
  77284. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  77285. /**
  77286. * Gets Camera field of view used by the Vignette effect.
  77287. */
  77288. get: function () {
  77289. return this.imageProcessingConfiguration.vignetteCameraFov;
  77290. },
  77291. /**
  77292. * Sets Camera field of view used by the Vignette effect.
  77293. */
  77294. set: function (value) {
  77295. this.imageProcessingConfiguration.vignetteCameraFov = value;
  77296. },
  77297. enumerable: true,
  77298. configurable: true
  77299. });
  77300. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  77301. /**
  77302. * Gets the vignette blend mode allowing different kind of effect.
  77303. */
  77304. get: function () {
  77305. return this.imageProcessingConfiguration.vignetteBlendMode;
  77306. },
  77307. /**
  77308. * Sets the vignette blend mode allowing different kind of effect.
  77309. */
  77310. set: function (value) {
  77311. this.imageProcessingConfiguration.vignetteBlendMode = value;
  77312. },
  77313. enumerable: true,
  77314. configurable: true
  77315. });
  77316. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  77317. /**
  77318. * Gets wether the vignette effect is enabled.
  77319. */
  77320. get: function () {
  77321. return this.imageProcessingConfiguration.vignetteEnabled;
  77322. },
  77323. /**
  77324. * Sets wether the vignette effect is enabled.
  77325. */
  77326. set: function (value) {
  77327. this.imageProcessingConfiguration.vignetteEnabled = value;
  77328. },
  77329. enumerable: true,
  77330. configurable: true
  77331. });
  77332. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  77333. /**
  77334. * Gets wether the input of the processing is in Gamma or Linear Space.
  77335. */
  77336. get: function () {
  77337. return this._fromLinearSpace;
  77338. },
  77339. /**
  77340. * Sets wether the input of the processing is in Gamma or Linear Space.
  77341. */
  77342. set: function (value) {
  77343. if (this._fromLinearSpace === value) {
  77344. return;
  77345. }
  77346. this._fromLinearSpace = value;
  77347. this._updateParameters();
  77348. },
  77349. enumerable: true,
  77350. configurable: true
  77351. });
  77352. ImageProcessingPostProcess.prototype.getClassName = function () {
  77353. return "ImageProcessingPostProcess";
  77354. };
  77355. ImageProcessingPostProcess.prototype._updateParameters = function () {
  77356. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  77357. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  77358. var defines = "";
  77359. for (var define in this._defines) {
  77360. if (this._defines[define]) {
  77361. defines += "#define " + define + ";\r\n";
  77362. }
  77363. }
  77364. var samplers = ["textureSampler"];
  77365. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  77366. var uniforms = ["scale"];
  77367. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  77368. this.updateEffect(defines, uniforms, samplers);
  77369. };
  77370. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  77371. _super.prototype.dispose.call(this, camera);
  77372. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  77373. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  77374. }
  77375. this.imageProcessingConfiguration.applyByPostProcess = false;
  77376. };
  77377. __decorate([
  77378. BABYLON.serialize()
  77379. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  77380. return ImageProcessingPostProcess;
  77381. }(BABYLON.PostProcess));
  77382. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  77383. })(BABYLON || (BABYLON = {}));
  77384. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  77385. var BABYLON;
  77386. (function (BABYLON) {
  77387. /**
  77388. * Class used to store bone information
  77389. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  77390. */
  77391. var Bone = /** @class */ (function (_super) {
  77392. __extends(Bone, _super);
  77393. /**
  77394. * Create a new bone
  77395. * @param name defines the bone name
  77396. * @param skeleton defines the parent skeleton
  77397. * @param parentBone defines the parent (can be null if the bone is the root)
  77398. * @param localMatrix defines the local matrix
  77399. * @param restPose defines the rest pose matrix
  77400. * @param baseMatrix defines the base matrix
  77401. * @param index defines index of the bone in the hiearchy
  77402. */
  77403. function Bone(
  77404. /**
  77405. * defines the bone name
  77406. */
  77407. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  77408. if (parentBone === void 0) { parentBone = null; }
  77409. if (localMatrix === void 0) { localMatrix = null; }
  77410. if (restPose === void 0) { restPose = null; }
  77411. if (baseMatrix === void 0) { baseMatrix = null; }
  77412. if (index === void 0) { index = null; }
  77413. var _this = _super.call(this, name, skeleton.getScene()) || this;
  77414. _this.name = name;
  77415. /**
  77416. * Gets the list of child bones
  77417. */
  77418. _this.children = new Array();
  77419. /** Gets the animations associated with this bone */
  77420. _this.animations = new Array();
  77421. /**
  77422. * @hidden Internal only
  77423. * Set this value to map this bone to a different index in the transform matrices
  77424. * Set this value to -1 to exclude the bone from the transform matrices
  77425. */
  77426. _this._index = null;
  77427. _this._absoluteTransform = new BABYLON.Matrix();
  77428. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  77429. _this._scalingDeterminant = 1;
  77430. _this._worldTransform = new BABYLON.Matrix();
  77431. _this._needToDecompose = true;
  77432. _this._needToCompose = false;
  77433. _this._skeleton = skeleton;
  77434. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  77435. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  77436. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  77437. _this._index = index;
  77438. skeleton.bones.push(_this);
  77439. _this.setParent(parentBone, false);
  77440. if (baseMatrix || localMatrix) {
  77441. _this._updateDifferenceMatrix();
  77442. }
  77443. return _this;
  77444. }
  77445. Object.defineProperty(Bone.prototype, "_matrix", {
  77446. /** @hidden */
  77447. get: function () {
  77448. this._compose();
  77449. return this._localMatrix;
  77450. },
  77451. /** @hidden */
  77452. set: function (value) {
  77453. this._localMatrix.copyFrom(value);
  77454. this._needToDecompose = true;
  77455. },
  77456. enumerable: true,
  77457. configurable: true
  77458. });
  77459. // Members
  77460. /**
  77461. * Gets the parent skeleton
  77462. * @returns a skeleton
  77463. */
  77464. Bone.prototype.getSkeleton = function () {
  77465. return this._skeleton;
  77466. };
  77467. /**
  77468. * Gets parent bone
  77469. * @returns a bone or null if the bone is the root of the bone hierarchy
  77470. */
  77471. Bone.prototype.getParent = function () {
  77472. return this._parent;
  77473. };
  77474. /**
  77475. * Sets the parent bone
  77476. * @param parent defines the parent (can be null if the bone is the root)
  77477. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  77478. */
  77479. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  77480. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  77481. if (this._parent === parent) {
  77482. return;
  77483. }
  77484. if (this._parent) {
  77485. var index = this._parent.children.indexOf(this);
  77486. if (index !== -1) {
  77487. this._parent.children.splice(index, 1);
  77488. }
  77489. }
  77490. this._parent = parent;
  77491. if (this._parent) {
  77492. this._parent.children.push(this);
  77493. }
  77494. if (updateDifferenceMatrix) {
  77495. this._updateDifferenceMatrix();
  77496. }
  77497. this.markAsDirty();
  77498. };
  77499. /**
  77500. * Gets the local matrix
  77501. * @returns a matrix
  77502. */
  77503. Bone.prototype.getLocalMatrix = function () {
  77504. this._compose();
  77505. return this._localMatrix;
  77506. };
  77507. /**
  77508. * Gets the base matrix (initial matrix which remains unchanged)
  77509. * @returns a matrix
  77510. */
  77511. Bone.prototype.getBaseMatrix = function () {
  77512. return this._baseMatrix;
  77513. };
  77514. /**
  77515. * Gets the rest pose matrix
  77516. * @returns a matrix
  77517. */
  77518. Bone.prototype.getRestPose = function () {
  77519. return this._restPose;
  77520. };
  77521. /**
  77522. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  77523. */
  77524. Bone.prototype.getWorldMatrix = function () {
  77525. return this._worldTransform;
  77526. };
  77527. /**
  77528. * Sets the local matrix to rest pose matrix
  77529. */
  77530. Bone.prototype.returnToRest = function () {
  77531. this.updateMatrix(this._restPose.clone());
  77532. };
  77533. /**
  77534. * Gets the inverse of the absolute transform matrix.
  77535. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  77536. * @returns a matrix
  77537. */
  77538. Bone.prototype.getInvertedAbsoluteTransform = function () {
  77539. return this._invertedAbsoluteTransform;
  77540. };
  77541. /**
  77542. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  77543. * @returns a matrix
  77544. */
  77545. Bone.prototype.getAbsoluteTransform = function () {
  77546. return this._absoluteTransform;
  77547. };
  77548. Object.defineProperty(Bone.prototype, "position", {
  77549. // Properties (matches AbstractMesh properties)
  77550. /** Gets or sets current position (in local space) */
  77551. get: function () {
  77552. this._decompose();
  77553. return this._localPosition;
  77554. },
  77555. set: function (newPosition) {
  77556. this._decompose();
  77557. this._localPosition.copyFrom(newPosition);
  77558. this._markAsDirtyAndCompose();
  77559. },
  77560. enumerable: true,
  77561. configurable: true
  77562. });
  77563. Object.defineProperty(Bone.prototype, "rotation", {
  77564. /** Gets or sets current rotation (in local space) */
  77565. get: function () {
  77566. return this.getRotation();
  77567. },
  77568. set: function (newRotation) {
  77569. this.setRotation(newRotation);
  77570. },
  77571. enumerable: true,
  77572. configurable: true
  77573. });
  77574. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  77575. /** Gets or sets current rotation quaternion (in local space) */
  77576. get: function () {
  77577. this._decompose();
  77578. return this._localRotation;
  77579. },
  77580. set: function (newRotation) {
  77581. this.setRotationQuaternion(newRotation);
  77582. },
  77583. enumerable: true,
  77584. configurable: true
  77585. });
  77586. Object.defineProperty(Bone.prototype, "scaling", {
  77587. /** Gets or sets current scaling (in local space) */
  77588. get: function () {
  77589. return this.getScale();
  77590. },
  77591. set: function (newScaling) {
  77592. this.setScale(newScaling);
  77593. },
  77594. enumerable: true,
  77595. configurable: true
  77596. });
  77597. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  77598. /**
  77599. * Gets the animation properties override
  77600. */
  77601. get: function () {
  77602. return this._skeleton.animationPropertiesOverride;
  77603. },
  77604. enumerable: true,
  77605. configurable: true
  77606. });
  77607. // Methods
  77608. Bone.prototype._decompose = function () {
  77609. if (!this._needToDecompose) {
  77610. return;
  77611. }
  77612. this._needToDecompose = false;
  77613. if (!this._localScaling) {
  77614. this._localScaling = BABYLON.Vector3.Zero();
  77615. this._localRotation = BABYLON.Quaternion.Zero();
  77616. this._localPosition = BABYLON.Vector3.Zero();
  77617. }
  77618. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  77619. };
  77620. Bone.prototype._compose = function () {
  77621. if (!this._needToCompose) {
  77622. return;
  77623. }
  77624. this._needToCompose = false;
  77625. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  77626. };
  77627. /**
  77628. * Update the base and local matrices
  77629. * @param matrix defines the new base or local matrix
  77630. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  77631. * @param updateLocalMatrix defines if the local matrix should be updated
  77632. */
  77633. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  77634. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  77635. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  77636. this._baseMatrix.copyFrom(matrix);
  77637. if (updateDifferenceMatrix) {
  77638. this._updateDifferenceMatrix();
  77639. }
  77640. if (updateLocalMatrix) {
  77641. this._localMatrix.copyFrom(matrix);
  77642. this._markAsDirtyAndDecompose();
  77643. }
  77644. else {
  77645. this.markAsDirty();
  77646. }
  77647. };
  77648. /** @hidden */
  77649. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  77650. if (updateChildren === void 0) { updateChildren = true; }
  77651. if (!rootMatrix) {
  77652. rootMatrix = this._baseMatrix;
  77653. }
  77654. if (this._parent) {
  77655. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  77656. }
  77657. else {
  77658. this._absoluteTransform.copyFrom(rootMatrix);
  77659. }
  77660. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  77661. if (updateChildren) {
  77662. for (var index = 0; index < this.children.length; index++) {
  77663. this.children[index]._updateDifferenceMatrix();
  77664. }
  77665. }
  77666. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  77667. };
  77668. /**
  77669. * Flag the bone as dirty (Forcing it to update everything)
  77670. */
  77671. Bone.prototype.markAsDirty = function () {
  77672. this._currentRenderId++;
  77673. this._childRenderId++;
  77674. this._skeleton._markAsDirty();
  77675. };
  77676. Bone.prototype._markAsDirtyAndCompose = function () {
  77677. this.markAsDirty();
  77678. this._needToCompose = true;
  77679. };
  77680. Bone.prototype._markAsDirtyAndDecompose = function () {
  77681. this.markAsDirty();
  77682. this._needToDecompose = true;
  77683. };
  77684. /**
  77685. * Copy an animation range from another bone
  77686. * @param source defines the source bone
  77687. * @param rangeName defines the range name to copy
  77688. * @param frameOffset defines the frame offset
  77689. * @param rescaleAsRequired defines if rescaling must be applied if required
  77690. * @param skelDimensionsRatio defines the scaling ratio
  77691. * @returns true if operation was successful
  77692. */
  77693. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  77694. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  77695. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  77696. // all animation may be coming from a library skeleton, so may need to create animation
  77697. if (this.animations.length === 0) {
  77698. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  77699. this.animations[0].setKeys([]);
  77700. }
  77701. // get animation info / verify there is such a range from the source bone
  77702. var sourceRange = source.animations[0].getRange(rangeName);
  77703. if (!sourceRange) {
  77704. return false;
  77705. }
  77706. var from = sourceRange.from;
  77707. var to = sourceRange.to;
  77708. var sourceKeys = source.animations[0].getKeys();
  77709. // rescaling prep
  77710. var sourceBoneLength = source.length;
  77711. var sourceParent = source.getParent();
  77712. var parent = this.getParent();
  77713. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  77714. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  77715. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  77716. var destKeys = this.animations[0].getKeys();
  77717. // loop vars declaration
  77718. var orig;
  77719. var origTranslation;
  77720. var mat;
  77721. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  77722. orig = sourceKeys[key];
  77723. if (orig.frame >= from && orig.frame <= to) {
  77724. if (rescaleAsRequired) {
  77725. mat = orig.value.clone();
  77726. // scale based on parent ratio, when bone has parent
  77727. if (parentScalingReqd) {
  77728. origTranslation = mat.getTranslation();
  77729. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  77730. // scale based on skeleton dimension ratio when root bone, and value is passed
  77731. }
  77732. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  77733. origTranslation = mat.getTranslation();
  77734. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  77735. // use original when root bone, and no data for skelDimensionsRatio
  77736. }
  77737. else {
  77738. mat = orig.value;
  77739. }
  77740. }
  77741. else {
  77742. mat = orig.value;
  77743. }
  77744. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  77745. }
  77746. }
  77747. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  77748. return true;
  77749. };
  77750. /**
  77751. * Translate the bone in local or world space
  77752. * @param vec The amount to translate the bone
  77753. * @param space The space that the translation is in
  77754. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77755. */
  77756. Bone.prototype.translate = function (vec, space, mesh) {
  77757. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77758. var lm = this.getLocalMatrix();
  77759. if (space == BABYLON.Space.LOCAL) {
  77760. lm.m[12] += vec.x;
  77761. lm.m[13] += vec.y;
  77762. lm.m[14] += vec.z;
  77763. }
  77764. else {
  77765. var wm = null;
  77766. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  77767. if (mesh) {
  77768. wm = mesh.getWorldMatrix();
  77769. }
  77770. this._skeleton.computeAbsoluteTransforms();
  77771. var tmat = Bone._tmpMats[0];
  77772. var tvec = Bone._tmpVecs[0];
  77773. if (this._parent) {
  77774. if (mesh && wm) {
  77775. tmat.copyFrom(this._parent.getAbsoluteTransform());
  77776. tmat.multiplyToRef(wm, tmat);
  77777. }
  77778. else {
  77779. tmat.copyFrom(this._parent.getAbsoluteTransform());
  77780. }
  77781. }
  77782. tmat.m[12] = 0;
  77783. tmat.m[13] = 0;
  77784. tmat.m[14] = 0;
  77785. tmat.invert();
  77786. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  77787. lm.m[12] += tvec.x;
  77788. lm.m[13] += tvec.y;
  77789. lm.m[14] += tvec.z;
  77790. }
  77791. this._markAsDirtyAndDecompose();
  77792. };
  77793. /**
  77794. * Set the postion of the bone in local or world space
  77795. * @param position The position to set the bone
  77796. * @param space The space that the position is in
  77797. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77798. */
  77799. Bone.prototype.setPosition = function (position, space, mesh) {
  77800. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77801. var lm = this.getLocalMatrix();
  77802. if (space == BABYLON.Space.LOCAL) {
  77803. lm.m[12] = position.x;
  77804. lm.m[13] = position.y;
  77805. lm.m[14] = position.z;
  77806. }
  77807. else {
  77808. var wm = null;
  77809. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  77810. if (mesh) {
  77811. wm = mesh.getWorldMatrix();
  77812. }
  77813. this._skeleton.computeAbsoluteTransforms();
  77814. var tmat = Bone._tmpMats[0];
  77815. var vec = Bone._tmpVecs[0];
  77816. if (this._parent) {
  77817. if (mesh && wm) {
  77818. tmat.copyFrom(this._parent.getAbsoluteTransform());
  77819. tmat.multiplyToRef(wm, tmat);
  77820. }
  77821. else {
  77822. tmat.copyFrom(this._parent.getAbsoluteTransform());
  77823. }
  77824. }
  77825. tmat.invert();
  77826. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  77827. lm.m[12] = vec.x;
  77828. lm.m[13] = vec.y;
  77829. lm.m[14] = vec.z;
  77830. }
  77831. this._markAsDirtyAndDecompose();
  77832. };
  77833. /**
  77834. * Set the absolute position of the bone (world space)
  77835. * @param position The position to set the bone
  77836. * @param mesh The mesh that this bone is attached to
  77837. */
  77838. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  77839. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  77840. };
  77841. /**
  77842. * Scale the bone on the x, y and z axes (in local space)
  77843. * @param x The amount to scale the bone on the x axis
  77844. * @param y The amount to scale the bone on the y axis
  77845. * @param z The amount to scale the bone on the z axis
  77846. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  77847. */
  77848. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  77849. if (scaleChildren === void 0) { scaleChildren = false; }
  77850. var locMat = this.getLocalMatrix();
  77851. // Apply new scaling on top of current local matrix
  77852. var scaleMat = Bone._tmpMats[0];
  77853. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  77854. scaleMat.multiplyToRef(locMat, locMat);
  77855. // Invert scaling matrix and apply the inverse to all children
  77856. scaleMat.invert();
  77857. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  77858. var child = _a[_i];
  77859. var cm = child.getLocalMatrix();
  77860. cm.multiplyToRef(scaleMat, cm);
  77861. cm.m[12] *= x;
  77862. cm.m[13] *= y;
  77863. cm.m[14] *= z;
  77864. child._markAsDirtyAndDecompose();
  77865. }
  77866. this._markAsDirtyAndDecompose();
  77867. if (scaleChildren) {
  77868. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  77869. var child = _c[_b];
  77870. child.scale(x, y, z, scaleChildren);
  77871. }
  77872. }
  77873. };
  77874. /**
  77875. * Set the bone scaling in local space
  77876. * @param scale defines the scaling vector
  77877. */
  77878. Bone.prototype.setScale = function (scale) {
  77879. this._decompose();
  77880. this._localScaling.copyFrom(scale);
  77881. this._markAsDirtyAndCompose();
  77882. };
  77883. /**
  77884. * Gets the current scaling in local space
  77885. * @returns the current scaling vector
  77886. */
  77887. Bone.prototype.getScale = function () {
  77888. this._decompose();
  77889. return this._localScaling;
  77890. };
  77891. /**
  77892. * Gets the current scaling in local space and stores it in a target vector
  77893. * @param result defines the target vector
  77894. */
  77895. Bone.prototype.getScaleToRef = function (result) {
  77896. this._decompose();
  77897. result.copyFrom(this._localScaling);
  77898. };
  77899. /**
  77900. * Set the yaw, pitch, and roll of the bone in local or world space
  77901. * @param yaw The rotation of the bone on the y axis
  77902. * @param pitch The rotation of the bone on the x axis
  77903. * @param roll The rotation of the bone on the z axis
  77904. * @param space The space that the axes of rotation are in
  77905. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77906. */
  77907. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  77908. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77909. if (space === BABYLON.Space.LOCAL) {
  77910. var quat = Bone._tmpQuat;
  77911. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  77912. this.setRotationQuaternion(quat, space, mesh);
  77913. return;
  77914. }
  77915. var rotMatInv = Bone._tmpMats[0];
  77916. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  77917. return;
  77918. }
  77919. var rotMat = Bone._tmpMats[1];
  77920. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  77921. rotMatInv.multiplyToRef(rotMat, rotMat);
  77922. this._rotateWithMatrix(rotMat, space, mesh);
  77923. };
  77924. /**
  77925. * Add a rotation to the bone on an axis in local or world space
  77926. * @param axis The axis to rotate the bone on
  77927. * @param amount The amount to rotate the bone
  77928. * @param space The space that the axis is in
  77929. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77930. */
  77931. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  77932. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77933. var rmat = Bone._tmpMats[0];
  77934. rmat.m[12] = 0;
  77935. rmat.m[13] = 0;
  77936. rmat.m[14] = 0;
  77937. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  77938. this._rotateWithMatrix(rmat, space, mesh);
  77939. };
  77940. /**
  77941. * Set the rotation of the bone to a particular axis angle in local or world space
  77942. * @param axis The axis to rotate the bone on
  77943. * @param angle The angle that the bone should be rotated to
  77944. * @param space The space that the axis is in
  77945. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77946. */
  77947. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  77948. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77949. if (space === BABYLON.Space.LOCAL) {
  77950. var quat = Bone._tmpQuat;
  77951. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  77952. this.setRotationQuaternion(quat, space, mesh);
  77953. return;
  77954. }
  77955. var rotMatInv = Bone._tmpMats[0];
  77956. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  77957. return;
  77958. }
  77959. var rotMat = Bone._tmpMats[1];
  77960. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  77961. rotMatInv.multiplyToRef(rotMat, rotMat);
  77962. this._rotateWithMatrix(rotMat, space, mesh);
  77963. };
  77964. /**
  77965. * Set the euler rotation of the bone in local of world space
  77966. * @param rotation The euler rotation that the bone should be set to
  77967. * @param space The space that the rotation is in
  77968. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77969. */
  77970. Bone.prototype.setRotation = function (rotation, space, mesh) {
  77971. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77972. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  77973. };
  77974. /**
  77975. * Set the quaternion rotation of the bone in local of world space
  77976. * @param quat The quaternion rotation that the bone should be set to
  77977. * @param space The space that the rotation is in
  77978. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77979. */
  77980. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  77981. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77982. if (space === BABYLON.Space.LOCAL) {
  77983. this._decompose();
  77984. this._localRotation.copyFrom(quat);
  77985. this._markAsDirtyAndCompose();
  77986. return;
  77987. }
  77988. var rotMatInv = Bone._tmpMats[0];
  77989. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  77990. return;
  77991. }
  77992. var rotMat = Bone._tmpMats[1];
  77993. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  77994. rotMatInv.multiplyToRef(rotMat, rotMat);
  77995. this._rotateWithMatrix(rotMat, space, mesh);
  77996. };
  77997. /**
  77998. * Set the rotation matrix of the bone in local of world space
  77999. * @param rotMat The rotation matrix that the bone should be set to
  78000. * @param space The space that the rotation is in
  78001. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78002. */
  78003. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  78004. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78005. if (space === BABYLON.Space.LOCAL) {
  78006. var quat = Bone._tmpQuat;
  78007. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  78008. this.setRotationQuaternion(quat, space, mesh);
  78009. return;
  78010. }
  78011. var rotMatInv = Bone._tmpMats[0];
  78012. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78013. return;
  78014. }
  78015. var rotMat2 = Bone._tmpMats[1];
  78016. rotMat2.copyFrom(rotMat);
  78017. rotMatInv.multiplyToRef(rotMat, rotMat2);
  78018. this._rotateWithMatrix(rotMat2, space, mesh);
  78019. };
  78020. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  78021. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78022. var lmat = this.getLocalMatrix();
  78023. var lx = lmat.m[12];
  78024. var ly = lmat.m[13];
  78025. var lz = lmat.m[14];
  78026. var parent = this.getParent();
  78027. var parentScale = Bone._tmpMats[3];
  78028. var parentScaleInv = Bone._tmpMats[4];
  78029. if (parent && space == BABYLON.Space.WORLD) {
  78030. if (mesh) {
  78031. parentScale.copyFrom(mesh.getWorldMatrix());
  78032. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  78033. }
  78034. else {
  78035. parentScale.copyFrom(parent.getAbsoluteTransform());
  78036. }
  78037. parentScaleInv.copyFrom(parentScale);
  78038. parentScaleInv.invert();
  78039. lmat.multiplyToRef(parentScale, lmat);
  78040. lmat.multiplyToRef(rmat, lmat);
  78041. lmat.multiplyToRef(parentScaleInv, lmat);
  78042. }
  78043. else {
  78044. if (space == BABYLON.Space.WORLD && mesh) {
  78045. parentScale.copyFrom(mesh.getWorldMatrix());
  78046. parentScaleInv.copyFrom(parentScale);
  78047. parentScaleInv.invert();
  78048. lmat.multiplyToRef(parentScale, lmat);
  78049. lmat.multiplyToRef(rmat, lmat);
  78050. lmat.multiplyToRef(parentScaleInv, lmat);
  78051. }
  78052. else {
  78053. lmat.multiplyToRef(rmat, lmat);
  78054. }
  78055. }
  78056. lmat.m[12] = lx;
  78057. lmat.m[13] = ly;
  78058. lmat.m[14] = lz;
  78059. this.computeAbsoluteTransforms();
  78060. this._markAsDirtyAndDecompose();
  78061. };
  78062. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  78063. var scaleMatrix = Bone._tmpMats[2];
  78064. rotMatInv.copyFrom(this.getAbsoluteTransform());
  78065. if (mesh) {
  78066. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  78067. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  78068. }
  78069. rotMatInv.invert();
  78070. if (isNaN(rotMatInv.m[0])) {
  78071. // Matrix failed to invert.
  78072. // This can happen if scale is zero for example.
  78073. return false;
  78074. }
  78075. scaleMatrix.m[0] *= this._scalingDeterminant;
  78076. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  78077. return true;
  78078. };
  78079. /**
  78080. * Get the position of the bone in local or world space
  78081. * @param space The space that the returned position is in
  78082. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78083. * @returns The position of the bone
  78084. */
  78085. Bone.prototype.getPosition = function (space, mesh) {
  78086. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78087. if (mesh === void 0) { mesh = null; }
  78088. var pos = BABYLON.Vector3.Zero();
  78089. this.getPositionToRef(space, mesh, pos);
  78090. return pos;
  78091. };
  78092. /**
  78093. * Copy the position of the bone to a vector3 in local or world space
  78094. * @param space The space that the returned position is in
  78095. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78096. * @param result The vector3 to copy the position to
  78097. */
  78098. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  78099. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78100. if (space == BABYLON.Space.LOCAL) {
  78101. var lm = this.getLocalMatrix();
  78102. result.x = lm.m[12];
  78103. result.y = lm.m[13];
  78104. result.z = lm.m[14];
  78105. }
  78106. else {
  78107. var wm = null;
  78108. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78109. if (mesh) {
  78110. wm = mesh.getWorldMatrix();
  78111. }
  78112. this._skeleton.computeAbsoluteTransforms();
  78113. var tmat = Bone._tmpMats[0];
  78114. if (mesh && wm) {
  78115. tmat.copyFrom(this.getAbsoluteTransform());
  78116. tmat.multiplyToRef(wm, tmat);
  78117. }
  78118. else {
  78119. tmat = this.getAbsoluteTransform();
  78120. }
  78121. result.x = tmat.m[12];
  78122. result.y = tmat.m[13];
  78123. result.z = tmat.m[14];
  78124. }
  78125. };
  78126. /**
  78127. * Get the absolute position of the bone (world space)
  78128. * @param mesh The mesh that this bone is attached to
  78129. * @returns The absolute position of the bone
  78130. */
  78131. Bone.prototype.getAbsolutePosition = function (mesh) {
  78132. if (mesh === void 0) { mesh = null; }
  78133. var pos = BABYLON.Vector3.Zero();
  78134. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  78135. return pos;
  78136. };
  78137. /**
  78138. * Copy the absolute position of the bone (world space) to the result param
  78139. * @param mesh The mesh that this bone is attached to
  78140. * @param result The vector3 to copy the absolute position to
  78141. */
  78142. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  78143. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  78144. };
  78145. /**
  78146. * Compute the absolute transforms of this bone and its children
  78147. */
  78148. Bone.prototype.computeAbsoluteTransforms = function () {
  78149. this._compose();
  78150. if (this._parent) {
  78151. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  78152. }
  78153. else {
  78154. this._absoluteTransform.copyFrom(this._localMatrix);
  78155. var poseMatrix = this._skeleton.getPoseMatrix();
  78156. if (poseMatrix) {
  78157. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  78158. }
  78159. }
  78160. var children = this.children;
  78161. var len = children.length;
  78162. for (var i = 0; i < len; i++) {
  78163. children[i].computeAbsoluteTransforms();
  78164. }
  78165. };
  78166. /**
  78167. * Get the world direction from an axis that is in the local space of the bone
  78168. * @param localAxis The local direction that is used to compute the world direction
  78169. * @param mesh The mesh that this bone is attached to
  78170. * @returns The world direction
  78171. */
  78172. Bone.prototype.getDirection = function (localAxis, mesh) {
  78173. if (mesh === void 0) { mesh = null; }
  78174. var result = BABYLON.Vector3.Zero();
  78175. this.getDirectionToRef(localAxis, mesh, result);
  78176. return result;
  78177. };
  78178. /**
  78179. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  78180. * @param localAxis The local direction that is used to compute the world direction
  78181. * @param mesh The mesh that this bone is attached to
  78182. * @param result The vector3 that the world direction will be copied to
  78183. */
  78184. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  78185. if (mesh === void 0) { mesh = null; }
  78186. var wm = null;
  78187. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78188. if (mesh) {
  78189. wm = mesh.getWorldMatrix();
  78190. }
  78191. this._skeleton.computeAbsoluteTransforms();
  78192. var mat = Bone._tmpMats[0];
  78193. mat.copyFrom(this.getAbsoluteTransform());
  78194. if (mesh && wm) {
  78195. mat.multiplyToRef(wm, mat);
  78196. }
  78197. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  78198. result.normalize();
  78199. };
  78200. /**
  78201. * Get the euler rotation of the bone in local or world space
  78202. * @param space The space that the rotation should be in
  78203. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78204. * @returns The euler rotation
  78205. */
  78206. Bone.prototype.getRotation = function (space, mesh) {
  78207. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78208. if (mesh === void 0) { mesh = null; }
  78209. var result = BABYLON.Vector3.Zero();
  78210. this.getRotationToRef(space, mesh, result);
  78211. return result;
  78212. };
  78213. /**
  78214. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  78215. * @param space The space that the rotation should be in
  78216. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78217. * @param result The vector3 that the rotation should be copied to
  78218. */
  78219. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  78220. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78221. if (mesh === void 0) { mesh = null; }
  78222. var quat = Bone._tmpQuat;
  78223. this.getRotationQuaternionToRef(space, mesh, quat);
  78224. quat.toEulerAnglesToRef(result);
  78225. };
  78226. /**
  78227. * Get the quaternion rotation of the bone in either local or world space
  78228. * @param space The space that the rotation should be in
  78229. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78230. * @returns The quaternion rotation
  78231. */
  78232. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  78233. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78234. if (mesh === void 0) { mesh = null; }
  78235. var result = BABYLON.Quaternion.Identity();
  78236. this.getRotationQuaternionToRef(space, mesh, result);
  78237. return result;
  78238. };
  78239. /**
  78240. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  78241. * @param space The space that the rotation should be in
  78242. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78243. * @param result The quaternion that the rotation should be copied to
  78244. */
  78245. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  78246. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78247. if (mesh === void 0) { mesh = null; }
  78248. if (space == BABYLON.Space.LOCAL) {
  78249. this._decompose();
  78250. result.copyFrom(this._localRotation);
  78251. }
  78252. else {
  78253. var mat = Bone._tmpMats[0];
  78254. var amat = this.getAbsoluteTransform();
  78255. if (mesh) {
  78256. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  78257. }
  78258. else {
  78259. mat.copyFrom(amat);
  78260. }
  78261. mat.m[0] *= this._scalingDeterminant;
  78262. mat.m[1] *= this._scalingDeterminant;
  78263. mat.m[2] *= this._scalingDeterminant;
  78264. mat.decompose(undefined, result, undefined);
  78265. }
  78266. };
  78267. /**
  78268. * Get the rotation matrix of the bone in local or world space
  78269. * @param space The space that the rotation should be in
  78270. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78271. * @returns The rotation matrix
  78272. */
  78273. Bone.prototype.getRotationMatrix = function (space, mesh) {
  78274. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78275. var result = BABYLON.Matrix.Identity();
  78276. this.getRotationMatrixToRef(space, mesh, result);
  78277. return result;
  78278. };
  78279. /**
  78280. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  78281. * @param space The space that the rotation should be in
  78282. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78283. * @param result The quaternion that the rotation should be copied to
  78284. */
  78285. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  78286. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78287. if (space == BABYLON.Space.LOCAL) {
  78288. this.getLocalMatrix().getRotationMatrixToRef(result);
  78289. }
  78290. else {
  78291. var mat = Bone._tmpMats[0];
  78292. var amat = this.getAbsoluteTransform();
  78293. if (mesh) {
  78294. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  78295. }
  78296. else {
  78297. mat.copyFrom(amat);
  78298. }
  78299. mat.m[0] *= this._scalingDeterminant;
  78300. mat.m[1] *= this._scalingDeterminant;
  78301. mat.m[2] *= this._scalingDeterminant;
  78302. mat.getRotationMatrixToRef(result);
  78303. }
  78304. };
  78305. /**
  78306. * Get the world position of a point that is in the local space of the bone
  78307. * @param position The local position
  78308. * @param mesh The mesh that this bone is attached to
  78309. * @returns The world position
  78310. */
  78311. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  78312. if (mesh === void 0) { mesh = null; }
  78313. var result = BABYLON.Vector3.Zero();
  78314. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  78315. return result;
  78316. };
  78317. /**
  78318. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  78319. * @param position The local position
  78320. * @param mesh The mesh that this bone is attached to
  78321. * @param result The vector3 that the world position should be copied to
  78322. */
  78323. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  78324. if (mesh === void 0) { mesh = null; }
  78325. var wm = null;
  78326. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78327. if (mesh) {
  78328. wm = mesh.getWorldMatrix();
  78329. }
  78330. this._skeleton.computeAbsoluteTransforms();
  78331. var tmat = Bone._tmpMats[0];
  78332. if (mesh && wm) {
  78333. tmat.copyFrom(this.getAbsoluteTransform());
  78334. tmat.multiplyToRef(wm, tmat);
  78335. }
  78336. else {
  78337. tmat = this.getAbsoluteTransform();
  78338. }
  78339. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  78340. };
  78341. /**
  78342. * Get the local position of a point that is in world space
  78343. * @param position The world position
  78344. * @param mesh The mesh that this bone is attached to
  78345. * @returns The local position
  78346. */
  78347. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  78348. if (mesh === void 0) { mesh = null; }
  78349. var result = BABYLON.Vector3.Zero();
  78350. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  78351. return result;
  78352. };
  78353. /**
  78354. * Get the local position of a point that is in world space and copy it to the result param
  78355. * @param position The world position
  78356. * @param mesh The mesh that this bone is attached to
  78357. * @param result The vector3 that the local position should be copied to
  78358. */
  78359. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  78360. if (mesh === void 0) { mesh = null; }
  78361. var wm = null;
  78362. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78363. if (mesh) {
  78364. wm = mesh.getWorldMatrix();
  78365. }
  78366. this._skeleton.computeAbsoluteTransforms();
  78367. var tmat = Bone._tmpMats[0];
  78368. tmat.copyFrom(this.getAbsoluteTransform());
  78369. if (mesh && wm) {
  78370. tmat.multiplyToRef(wm, tmat);
  78371. }
  78372. tmat.invert();
  78373. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  78374. };
  78375. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78376. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  78377. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  78378. return Bone;
  78379. }(BABYLON.Node));
  78380. BABYLON.Bone = Bone;
  78381. })(BABYLON || (BABYLON = {}));
  78382. //# sourceMappingURL=babylon.bone.js.map
  78383. var BABYLON;
  78384. (function (BABYLON) {
  78385. /**
  78386. * Class used to apply inverse kinematics to bones
  78387. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  78388. */
  78389. var BoneIKController = /** @class */ (function () {
  78390. /**
  78391. * Creates a new BoneIKController
  78392. * @param mesh defines the mesh to control
  78393. * @param bone defines the bone to control
  78394. * @param options defines options to set up the controller
  78395. */
  78396. function BoneIKController(mesh, bone, options) {
  78397. /**
  78398. * Gets or sets the target position
  78399. */
  78400. this.targetPosition = BABYLON.Vector3.Zero();
  78401. /**
  78402. * Gets or sets the pole target position
  78403. */
  78404. this.poleTargetPosition = BABYLON.Vector3.Zero();
  78405. /**
  78406. * Gets or sets the pole target local offset
  78407. */
  78408. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  78409. /**
  78410. * Gets or sets the pole angle
  78411. */
  78412. this.poleAngle = 0;
  78413. /**
  78414. * 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)
  78415. */
  78416. this.slerpAmount = 1;
  78417. this._bone1Quat = BABYLON.Quaternion.Identity();
  78418. this._bone1Mat = BABYLON.Matrix.Identity();
  78419. this._bone2Ang = Math.PI;
  78420. this._maxAngle = Math.PI;
  78421. this._rightHandedSystem = false;
  78422. this._bendAxis = BABYLON.Vector3.Right();
  78423. this._slerping = false;
  78424. this._adjustRoll = 0;
  78425. this._bone2 = bone;
  78426. this._bone1 = bone.getParent();
  78427. if (!this._bone1) {
  78428. return;
  78429. }
  78430. this.mesh = mesh;
  78431. var bonePos = bone.getPosition();
  78432. if (bone.getAbsoluteTransform().determinant() > 0) {
  78433. this._rightHandedSystem = true;
  78434. this._bendAxis.x = 0;
  78435. this._bendAxis.y = 0;
  78436. this._bendAxis.z = -1;
  78437. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  78438. this._adjustRoll = Math.PI * .5;
  78439. this._bendAxis.z = 1;
  78440. }
  78441. }
  78442. if (this._bone1.length) {
  78443. var boneScale1 = this._bone1.getScale();
  78444. var boneScale2 = this._bone2.getScale();
  78445. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  78446. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  78447. }
  78448. else if (this._bone1.children[0]) {
  78449. mesh.computeWorldMatrix(true);
  78450. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  78451. var pos2 = this._bone2.getAbsolutePosition(mesh);
  78452. var pos3 = this._bone1.getAbsolutePosition(mesh);
  78453. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  78454. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  78455. }
  78456. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  78457. this.maxAngle = Math.PI;
  78458. if (options) {
  78459. if (options.targetMesh) {
  78460. this.targetMesh = options.targetMesh;
  78461. this.targetMesh.computeWorldMatrix(true);
  78462. }
  78463. if (options.poleTargetMesh) {
  78464. this.poleTargetMesh = options.poleTargetMesh;
  78465. this.poleTargetMesh.computeWorldMatrix(true);
  78466. }
  78467. else if (options.poleTargetBone) {
  78468. this.poleTargetBone = options.poleTargetBone;
  78469. }
  78470. else if (this._bone1.getParent()) {
  78471. this.poleTargetBone = this._bone1.getParent();
  78472. }
  78473. if (options.poleTargetLocalOffset) {
  78474. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  78475. }
  78476. if (options.poleAngle) {
  78477. this.poleAngle = options.poleAngle;
  78478. }
  78479. if (options.bendAxis) {
  78480. this._bendAxis.copyFrom(options.bendAxis);
  78481. }
  78482. if (options.maxAngle) {
  78483. this.maxAngle = options.maxAngle;
  78484. }
  78485. if (options.slerpAmount) {
  78486. this.slerpAmount = options.slerpAmount;
  78487. }
  78488. }
  78489. }
  78490. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  78491. /**
  78492. * Gets or sets maximum allowed angle
  78493. */
  78494. get: function () {
  78495. return this._maxAngle;
  78496. },
  78497. set: function (value) {
  78498. this._setMaxAngle(value);
  78499. },
  78500. enumerable: true,
  78501. configurable: true
  78502. });
  78503. BoneIKController.prototype._setMaxAngle = function (ang) {
  78504. if (ang < 0) {
  78505. ang = 0;
  78506. }
  78507. if (ang > Math.PI || ang == undefined) {
  78508. ang = Math.PI;
  78509. }
  78510. this._maxAngle = ang;
  78511. var a = this._bone1Length;
  78512. var b = this._bone2Length;
  78513. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  78514. };
  78515. /**
  78516. * Force the controller to update the bones
  78517. */
  78518. BoneIKController.prototype.update = function () {
  78519. var bone1 = this._bone1;
  78520. if (!bone1) {
  78521. return;
  78522. }
  78523. var target = this.targetPosition;
  78524. var poleTarget = this.poleTargetPosition;
  78525. var mat1 = BoneIKController._tmpMats[0];
  78526. var mat2 = BoneIKController._tmpMats[1];
  78527. if (this.targetMesh) {
  78528. target.copyFrom(this.targetMesh.getAbsolutePosition());
  78529. }
  78530. if (this.poleTargetBone) {
  78531. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  78532. }
  78533. else if (this.poleTargetMesh) {
  78534. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  78535. }
  78536. var bonePos = BoneIKController._tmpVecs[0];
  78537. var zaxis = BoneIKController._tmpVecs[1];
  78538. var xaxis = BoneIKController._tmpVecs[2];
  78539. var yaxis = BoneIKController._tmpVecs[3];
  78540. var upAxis = BoneIKController._tmpVecs[4];
  78541. var _tmpQuat = BoneIKController._tmpQuat;
  78542. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  78543. poleTarget.subtractToRef(bonePos, upAxis);
  78544. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  78545. upAxis.y = 1;
  78546. }
  78547. else {
  78548. upAxis.normalize();
  78549. }
  78550. target.subtractToRef(bonePos, yaxis);
  78551. yaxis.normalize();
  78552. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  78553. zaxis.normalize();
  78554. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  78555. xaxis.normalize();
  78556. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  78557. var a = this._bone1Length;
  78558. var b = this._bone2Length;
  78559. var c = BABYLON.Vector3.Distance(bonePos, target);
  78560. if (this._maxReach > 0) {
  78561. c = Math.min(this._maxReach, c);
  78562. }
  78563. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  78564. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  78565. if (acosa > 1) {
  78566. acosa = 1;
  78567. }
  78568. if (acosb > 1) {
  78569. acosb = 1;
  78570. }
  78571. if (acosa < -1) {
  78572. acosa = -1;
  78573. }
  78574. if (acosb < -1) {
  78575. acosb = -1;
  78576. }
  78577. var angA = Math.acos(acosa);
  78578. var angB = Math.acos(acosb);
  78579. var angC = -angA - angB;
  78580. if (this._rightHandedSystem) {
  78581. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  78582. mat2.multiplyToRef(mat1, mat1);
  78583. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  78584. mat2.multiplyToRef(mat1, mat1);
  78585. }
  78586. else {
  78587. var _tmpVec = BoneIKController._tmpVecs[5];
  78588. _tmpVec.copyFrom(this._bendAxis);
  78589. _tmpVec.x *= -1;
  78590. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  78591. mat2.multiplyToRef(mat1, mat1);
  78592. }
  78593. if (this.poleAngle) {
  78594. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  78595. mat1.multiplyToRef(mat2, mat1);
  78596. }
  78597. if (this._bone1) {
  78598. if (this.slerpAmount < 1) {
  78599. if (!this._slerping) {
  78600. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  78601. }
  78602. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  78603. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  78604. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  78605. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  78606. this._slerping = true;
  78607. }
  78608. else {
  78609. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  78610. this._bone1Mat.copyFrom(mat1);
  78611. this._slerping = false;
  78612. }
  78613. }
  78614. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  78615. this._bone2Ang = angC;
  78616. };
  78617. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78618. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  78619. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  78620. return BoneIKController;
  78621. }());
  78622. BABYLON.BoneIKController = BoneIKController;
  78623. })(BABYLON || (BABYLON = {}));
  78624. //# sourceMappingURL=babylon.boneIKController.js.map
  78625. var BABYLON;
  78626. (function (BABYLON) {
  78627. /**
  78628. * Class used to make a bone look toward a point in space
  78629. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  78630. */
  78631. var BoneLookController = /** @class */ (function () {
  78632. /**
  78633. * Create a BoneLookController
  78634. * @param mesh the mesh that the bone belongs to
  78635. * @param bone the bone that will be looking to the target
  78636. * @param target the target Vector3 to look at
  78637. * @param settings optional settings:
  78638. * * maxYaw: the maximum angle the bone will yaw to
  78639. * * minYaw: the minimum angle the bone will yaw to
  78640. * * maxPitch: the maximum angle the bone will pitch to
  78641. * * minPitch: the minimum angle the bone will yaw to
  78642. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  78643. * * upAxis: the up axis of the coordinate system
  78644. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  78645. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  78646. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  78647. * * adjustYaw: used to make an adjustment to the yaw of the bone
  78648. * * adjustPitch: used to make an adjustment to the pitch of the bone
  78649. * * adjustRoll: used to make an adjustment to the roll of the bone
  78650. **/
  78651. function BoneLookController(mesh, bone, target, options) {
  78652. /**
  78653. * The up axis of the coordinate system that is used when the bone is rotated
  78654. */
  78655. this.upAxis = BABYLON.Vector3.Up();
  78656. /**
  78657. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  78658. */
  78659. this.upAxisSpace = BABYLON.Space.LOCAL;
  78660. /**
  78661. * Used to make an adjustment to the yaw of the bone
  78662. */
  78663. this.adjustYaw = 0;
  78664. /**
  78665. * Used to make an adjustment to the pitch of the bone
  78666. */
  78667. this.adjustPitch = 0;
  78668. /**
  78669. * Used to make an adjustment to the roll of the bone
  78670. */
  78671. this.adjustRoll = 0;
  78672. /**
  78673. * 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)
  78674. */
  78675. this.slerpAmount = 1;
  78676. this._boneQuat = BABYLON.Quaternion.Identity();
  78677. this._slerping = false;
  78678. this._firstFrameSkipped = false;
  78679. this._fowardAxis = BABYLON.Vector3.Forward();
  78680. this.mesh = mesh;
  78681. this.bone = bone;
  78682. this.target = target;
  78683. if (options) {
  78684. if (options.adjustYaw) {
  78685. this.adjustYaw = options.adjustYaw;
  78686. }
  78687. if (options.adjustPitch) {
  78688. this.adjustPitch = options.adjustPitch;
  78689. }
  78690. if (options.adjustRoll) {
  78691. this.adjustRoll = options.adjustRoll;
  78692. }
  78693. if (options.maxYaw != null) {
  78694. this.maxYaw = options.maxYaw;
  78695. }
  78696. else {
  78697. this.maxYaw = Math.PI;
  78698. }
  78699. if (options.minYaw != null) {
  78700. this.minYaw = options.minYaw;
  78701. }
  78702. else {
  78703. this.minYaw = -Math.PI;
  78704. }
  78705. if (options.maxPitch != null) {
  78706. this.maxPitch = options.maxPitch;
  78707. }
  78708. else {
  78709. this.maxPitch = Math.PI;
  78710. }
  78711. if (options.minPitch != null) {
  78712. this.minPitch = options.minPitch;
  78713. }
  78714. else {
  78715. this.minPitch = -Math.PI;
  78716. }
  78717. if (options.slerpAmount != null) {
  78718. this.slerpAmount = options.slerpAmount;
  78719. }
  78720. if (options.upAxis != null) {
  78721. this.upAxis = options.upAxis;
  78722. }
  78723. if (options.upAxisSpace != null) {
  78724. this.upAxisSpace = options.upAxisSpace;
  78725. }
  78726. if (options.yawAxis != null || options.pitchAxis != null) {
  78727. var newYawAxis = BABYLON.Axis.Y;
  78728. var newPitchAxis = BABYLON.Axis.X;
  78729. if (options.yawAxis != null) {
  78730. newYawAxis = options.yawAxis.clone();
  78731. newYawAxis.normalize();
  78732. }
  78733. if (options.pitchAxis != null) {
  78734. newPitchAxis = options.pitchAxis.clone();
  78735. newPitchAxis.normalize();
  78736. }
  78737. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  78738. this._transformYawPitch = BABYLON.Matrix.Identity();
  78739. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  78740. this._transformYawPitchInv = this._transformYawPitch.clone();
  78741. this._transformYawPitch.invert();
  78742. }
  78743. }
  78744. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  78745. this.upAxisSpace = BABYLON.Space.LOCAL;
  78746. }
  78747. }
  78748. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  78749. /**
  78750. * Gets or sets the minimum yaw angle that the bone can look to
  78751. */
  78752. get: function () {
  78753. return this._minYaw;
  78754. },
  78755. set: function (value) {
  78756. this._minYaw = value;
  78757. this._minYawSin = Math.sin(value);
  78758. this._minYawCos = Math.cos(value);
  78759. if (this._maxYaw != null) {
  78760. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  78761. this._yawRange = this._maxYaw - this._minYaw;
  78762. }
  78763. },
  78764. enumerable: true,
  78765. configurable: true
  78766. });
  78767. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  78768. /**
  78769. * Gets or sets the maximum yaw angle that the bone can look to
  78770. */
  78771. get: function () {
  78772. return this._maxYaw;
  78773. },
  78774. set: function (value) {
  78775. this._maxYaw = value;
  78776. this._maxYawSin = Math.sin(value);
  78777. this._maxYawCos = Math.cos(value);
  78778. if (this._minYaw != null) {
  78779. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  78780. this._yawRange = this._maxYaw - this._minYaw;
  78781. }
  78782. },
  78783. enumerable: true,
  78784. configurable: true
  78785. });
  78786. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  78787. /**
  78788. * Gets or sets the minimum pitch angle that the bone can look to
  78789. */
  78790. get: function () {
  78791. return this._minPitch;
  78792. },
  78793. set: function (value) {
  78794. this._minPitch = value;
  78795. this._minPitchTan = Math.tan(value);
  78796. },
  78797. enumerable: true,
  78798. configurable: true
  78799. });
  78800. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  78801. /**
  78802. * Gets or sets the maximum pitch angle that the bone can look to
  78803. */
  78804. get: function () {
  78805. return this._maxPitch;
  78806. },
  78807. set: function (value) {
  78808. this._maxPitch = value;
  78809. this._maxPitchTan = Math.tan(value);
  78810. },
  78811. enumerable: true,
  78812. configurable: true
  78813. });
  78814. /**
  78815. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  78816. */
  78817. BoneLookController.prototype.update = function () {
  78818. //skip the first frame when slerping so that the mesh rotation is correct
  78819. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  78820. this._firstFrameSkipped = true;
  78821. return;
  78822. }
  78823. var bone = this.bone;
  78824. var bonePos = BoneLookController._tmpVecs[0];
  78825. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  78826. var target = this.target;
  78827. var _tmpMat1 = BoneLookController._tmpMats[0];
  78828. var _tmpMat2 = BoneLookController._tmpMats[1];
  78829. var mesh = this.mesh;
  78830. var parentBone = bone.getParent();
  78831. var upAxis = BoneLookController._tmpVecs[1];
  78832. upAxis.copyFrom(this.upAxis);
  78833. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  78834. if (this._transformYawPitch) {
  78835. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  78836. }
  78837. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  78838. }
  78839. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  78840. mesh.getDirectionToRef(upAxis, upAxis);
  78841. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  78842. upAxis.normalize();
  78843. }
  78844. }
  78845. var checkYaw = false;
  78846. var checkPitch = false;
  78847. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  78848. checkYaw = true;
  78849. }
  78850. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  78851. checkPitch = true;
  78852. }
  78853. if (checkYaw || checkPitch) {
  78854. var spaceMat = BoneLookController._tmpMats[2];
  78855. var spaceMatInv = BoneLookController._tmpMats[3];
  78856. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  78857. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  78858. }
  78859. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  78860. spaceMat.copyFrom(mesh.getWorldMatrix());
  78861. }
  78862. else {
  78863. var forwardAxis = BoneLookController._tmpVecs[2];
  78864. forwardAxis.copyFrom(this._fowardAxis);
  78865. if (this._transformYawPitch) {
  78866. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  78867. }
  78868. if (parentBone) {
  78869. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  78870. }
  78871. else {
  78872. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  78873. }
  78874. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  78875. rightAxis.normalize();
  78876. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  78877. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  78878. }
  78879. spaceMat.invertToRef(spaceMatInv);
  78880. var xzlen = null;
  78881. if (checkPitch) {
  78882. var localTarget = BoneLookController._tmpVecs[3];
  78883. target.subtractToRef(bonePos, localTarget);
  78884. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  78885. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  78886. var pitch = Math.atan2(localTarget.y, xzlen);
  78887. var newPitch = pitch;
  78888. if (pitch > this._maxPitch) {
  78889. localTarget.y = this._maxPitchTan * xzlen;
  78890. newPitch = this._maxPitch;
  78891. }
  78892. else if (pitch < this._minPitch) {
  78893. localTarget.y = this._minPitchTan * xzlen;
  78894. newPitch = this._minPitch;
  78895. }
  78896. if (pitch != newPitch) {
  78897. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  78898. localTarget.addInPlace(bonePos);
  78899. target = localTarget;
  78900. }
  78901. }
  78902. if (checkYaw) {
  78903. var localTarget = BoneLookController._tmpVecs[4];
  78904. target.subtractToRef(bonePos, localTarget);
  78905. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  78906. var yaw = Math.atan2(localTarget.x, localTarget.z);
  78907. var newYaw = yaw;
  78908. if (yaw > this._maxYaw || yaw < this._minYaw) {
  78909. if (xzlen == null) {
  78910. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  78911. }
  78912. if (this._yawRange > Math.PI) {
  78913. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  78914. localTarget.z = this._maxYawCos * xzlen;
  78915. localTarget.x = this._maxYawSin * xzlen;
  78916. newYaw = this._maxYaw;
  78917. }
  78918. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  78919. localTarget.z = this._minYawCos * xzlen;
  78920. localTarget.x = this._minYawSin * xzlen;
  78921. newYaw = this._minYaw;
  78922. }
  78923. }
  78924. else {
  78925. if (yaw > this._maxYaw) {
  78926. localTarget.z = this._maxYawCos * xzlen;
  78927. localTarget.x = this._maxYawSin * xzlen;
  78928. newYaw = this._maxYaw;
  78929. }
  78930. else if (yaw < this._minYaw) {
  78931. localTarget.z = this._minYawCos * xzlen;
  78932. localTarget.x = this._minYawSin * xzlen;
  78933. newYaw = this._minYaw;
  78934. }
  78935. }
  78936. }
  78937. if (this._slerping && this._yawRange > Math.PI) {
  78938. //are we going to be crossing into the min/max region?
  78939. var boneFwd = BoneLookController._tmpVecs[8];
  78940. boneFwd.copyFrom(BABYLON.Axis.Z);
  78941. if (this._transformYawPitch) {
  78942. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  78943. }
  78944. var boneRotMat = BoneLookController._tmpMats[4];
  78945. this._boneQuat.toRotationMatrix(boneRotMat);
  78946. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  78947. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  78948. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  78949. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  78950. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  78951. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  78952. if (angBtwTar > angBtwMidYaw) {
  78953. if (xzlen == null) {
  78954. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  78955. }
  78956. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  78957. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  78958. if (angBtwMin < angBtwMax) {
  78959. newYaw = boneYaw + Math.PI * .75;
  78960. localTarget.z = Math.cos(newYaw) * xzlen;
  78961. localTarget.x = Math.sin(newYaw) * xzlen;
  78962. }
  78963. else {
  78964. newYaw = boneYaw - Math.PI * .75;
  78965. localTarget.z = Math.cos(newYaw) * xzlen;
  78966. localTarget.x = Math.sin(newYaw) * xzlen;
  78967. }
  78968. }
  78969. }
  78970. if (yaw != newYaw) {
  78971. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  78972. localTarget.addInPlace(bonePos);
  78973. target = localTarget;
  78974. }
  78975. }
  78976. }
  78977. var zaxis = BoneLookController._tmpVecs[5];
  78978. var xaxis = BoneLookController._tmpVecs[6];
  78979. var yaxis = BoneLookController._tmpVecs[7];
  78980. var _tmpQuat = BoneLookController._tmpQuat;
  78981. target.subtractToRef(bonePos, zaxis);
  78982. zaxis.normalize();
  78983. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  78984. xaxis.normalize();
  78985. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  78986. yaxis.normalize();
  78987. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  78988. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  78989. return;
  78990. }
  78991. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  78992. return;
  78993. }
  78994. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  78995. return;
  78996. }
  78997. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  78998. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  78999. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  79000. }
  79001. if (this.slerpAmount < 1) {
  79002. if (!this._slerping) {
  79003. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  79004. }
  79005. if (this._transformYawPitch) {
  79006. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  79007. }
  79008. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  79009. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  79010. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  79011. this._slerping = true;
  79012. }
  79013. else {
  79014. if (this._transformYawPitch) {
  79015. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  79016. }
  79017. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  79018. this._slerping = false;
  79019. }
  79020. };
  79021. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  79022. var angDiff = ang2 - ang1;
  79023. angDiff %= Math.PI * 2;
  79024. if (angDiff > Math.PI) {
  79025. angDiff -= Math.PI * 2;
  79026. }
  79027. else if (angDiff < -Math.PI) {
  79028. angDiff += Math.PI * 2;
  79029. }
  79030. return angDiff;
  79031. };
  79032. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  79033. ang1 %= (2 * Math.PI);
  79034. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  79035. ang2 %= (2 * Math.PI);
  79036. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  79037. var ab = 0;
  79038. if (ang1 < ang2) {
  79039. ab = ang2 - ang1;
  79040. }
  79041. else {
  79042. ab = ang1 - ang2;
  79043. }
  79044. if (ab > Math.PI) {
  79045. ab = Math.PI * 2 - ab;
  79046. }
  79047. return ab;
  79048. };
  79049. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  79050. ang %= (2 * Math.PI);
  79051. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  79052. ang1 %= (2 * Math.PI);
  79053. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  79054. ang2 %= (2 * Math.PI);
  79055. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  79056. if (ang1 < ang2) {
  79057. if (ang > ang1 && ang < ang2) {
  79058. return true;
  79059. }
  79060. }
  79061. else {
  79062. if (ang > ang2 && ang < ang1) {
  79063. return true;
  79064. }
  79065. }
  79066. return false;
  79067. };
  79068. 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()];
  79069. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  79070. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  79071. return BoneLookController;
  79072. }());
  79073. BABYLON.BoneLookController = BoneLookController;
  79074. })(BABYLON || (BABYLON = {}));
  79075. //# sourceMappingURL=babylon.boneLookController.js.map
  79076. var BABYLON;
  79077. (function (BABYLON) {
  79078. /**
  79079. * Class used to handle skinning animations
  79080. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  79081. */
  79082. var Skeleton = /** @class */ (function () {
  79083. /**
  79084. * Creates a new skeleton
  79085. * @param name defines the skeleton name
  79086. * @param id defines the skeleton Id
  79087. * @param scene defines the hosting scene
  79088. */
  79089. function Skeleton(
  79090. /** defines the skeleton name */
  79091. name,
  79092. /** defines the skeleton Id */
  79093. id, scene) {
  79094. this.name = name;
  79095. this.id = id;
  79096. /**
  79097. * Gets the list of child bones
  79098. */
  79099. this.bones = new Array();
  79100. /**
  79101. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  79102. */
  79103. this.needInitialSkinMatrix = false;
  79104. this._isDirty = true;
  79105. this._meshesWithPoseMatrix = new Array();
  79106. this._identity = BABYLON.Matrix.Identity();
  79107. this._ranges = {};
  79108. this._lastAbsoluteTransformsUpdateId = -1;
  79109. /**
  79110. * Specifies if the skeleton should be serialized
  79111. */
  79112. this.doNotSerialize = false;
  79113. this._animationPropertiesOverride = null;
  79114. // Events
  79115. /**
  79116. * An observable triggered before computing the skeleton's matrices
  79117. */
  79118. this.onBeforeComputeObservable = new BABYLON.Observable();
  79119. this.bones = [];
  79120. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  79121. scene.skeletons.push(this);
  79122. //make sure it will recalculate the matrix next time prepare is called.
  79123. this._isDirty = true;
  79124. }
  79125. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  79126. /**
  79127. * Gets or sets the animation properties override
  79128. */
  79129. get: function () {
  79130. if (!this._animationPropertiesOverride) {
  79131. return this._scene.animationPropertiesOverride;
  79132. }
  79133. return this._animationPropertiesOverride;
  79134. },
  79135. set: function (value) {
  79136. this._animationPropertiesOverride = value;
  79137. },
  79138. enumerable: true,
  79139. configurable: true
  79140. });
  79141. // Members
  79142. /**
  79143. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  79144. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  79145. * @returns a Float32Array containing matrices data
  79146. */
  79147. Skeleton.prototype.getTransformMatrices = function (mesh) {
  79148. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  79149. return mesh._bonesTransformMatrices;
  79150. }
  79151. if (!this._transformMatrices) {
  79152. this.prepare();
  79153. }
  79154. return this._transformMatrices;
  79155. };
  79156. /**
  79157. * Gets the current hosting scene
  79158. * @returns a scene object
  79159. */
  79160. Skeleton.prototype.getScene = function () {
  79161. return this._scene;
  79162. };
  79163. // Methods
  79164. /**
  79165. * Gets a string representing the current skeleton data
  79166. * @param fullDetails defines a boolean indicating if we want a verbose version
  79167. * @returns a string representing the current skeleton data
  79168. */
  79169. Skeleton.prototype.toString = function (fullDetails) {
  79170. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  79171. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  79172. if (fullDetails) {
  79173. ret += ", Ranges: {";
  79174. var first = true;
  79175. for (var name_1 in this._ranges) {
  79176. if (first) {
  79177. ret += ", ";
  79178. first = false;
  79179. }
  79180. ret += name_1;
  79181. }
  79182. ret += "}";
  79183. }
  79184. return ret;
  79185. };
  79186. /**
  79187. * Get bone's index searching by name
  79188. * @param name defines bone's name to search for
  79189. * @return the indice of the bone. Returns -1 if not found
  79190. */
  79191. Skeleton.prototype.getBoneIndexByName = function (name) {
  79192. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  79193. if (this.bones[boneIndex].name === name) {
  79194. return boneIndex;
  79195. }
  79196. }
  79197. return -1;
  79198. };
  79199. /**
  79200. * Creater a new animation range
  79201. * @param name defines the name of the range
  79202. * @param from defines the start key
  79203. * @param to defines the end key
  79204. */
  79205. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  79206. // check name not already in use
  79207. if (!this._ranges[name]) {
  79208. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  79209. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  79210. if (this.bones[i].animations[0]) {
  79211. this.bones[i].animations[0].createRange(name, from, to);
  79212. }
  79213. }
  79214. }
  79215. };
  79216. /**
  79217. * Delete a specific animation range
  79218. * @param name defines the name of the range
  79219. * @param deleteFrames defines if frames must be removed as well
  79220. */
  79221. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  79222. if (deleteFrames === void 0) { deleteFrames = true; }
  79223. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  79224. if (this.bones[i].animations[0]) {
  79225. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  79226. }
  79227. }
  79228. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  79229. };
  79230. /**
  79231. * Gets a specific animation range
  79232. * @param name defines the name of the range to look for
  79233. * @returns the requested animation range or null if not found
  79234. */
  79235. Skeleton.prototype.getAnimationRange = function (name) {
  79236. return this._ranges[name];
  79237. };
  79238. /**
  79239. * Gets the list of all animation ranges defined on this skeleton
  79240. * @returns an array
  79241. */
  79242. Skeleton.prototype.getAnimationRanges = function () {
  79243. var animationRanges = [];
  79244. var name;
  79245. var i = 0;
  79246. for (name in this._ranges) {
  79247. animationRanges[i] = this._ranges[name];
  79248. i++;
  79249. }
  79250. return animationRanges;
  79251. };
  79252. /**
  79253. * Copy animation range from a source skeleton.
  79254. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  79255. * @param source defines the source skeleton
  79256. * @param name defines the name of the range to copy
  79257. * @param rescaleAsRequired defines if rescaling must be applied if required
  79258. * @returns true if operation was successful
  79259. */
  79260. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  79261. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  79262. if (this._ranges[name] || !source.getAnimationRange(name)) {
  79263. return false;
  79264. }
  79265. var ret = true;
  79266. var frameOffset = this._getHighestAnimationFrame() + 1;
  79267. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  79268. var boneDict = {};
  79269. var sourceBones = source.bones;
  79270. var nBones;
  79271. var i;
  79272. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  79273. boneDict[sourceBones[i].name] = sourceBones[i];
  79274. }
  79275. if (this.bones.length !== sourceBones.length) {
  79276. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  79277. ret = false;
  79278. }
  79279. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  79280. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  79281. var boneName = this.bones[i].name;
  79282. var sourceBone = boneDict[boneName];
  79283. if (sourceBone) {
  79284. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  79285. }
  79286. else {
  79287. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  79288. ret = false;
  79289. }
  79290. }
  79291. // do not call createAnimationRange(), since it also is done to bones, which was already done
  79292. var range = source.getAnimationRange(name);
  79293. if (range) {
  79294. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  79295. }
  79296. return ret;
  79297. };
  79298. /**
  79299. * Forces the skeleton to go to rest pose
  79300. */
  79301. Skeleton.prototype.returnToRest = function () {
  79302. for (var index = 0; index < this.bones.length; index++) {
  79303. this.bones[index].returnToRest();
  79304. }
  79305. };
  79306. Skeleton.prototype._getHighestAnimationFrame = function () {
  79307. var ret = 0;
  79308. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  79309. if (this.bones[i].animations[0]) {
  79310. var highest = this.bones[i].animations[0].getHighestFrame();
  79311. if (ret < highest) {
  79312. ret = highest;
  79313. }
  79314. }
  79315. }
  79316. return ret;
  79317. };
  79318. /**
  79319. * Begin a specific animation range
  79320. * @param name defines the name of the range to start
  79321. * @param loop defines if looping must be turned on (false by default)
  79322. * @param speedRatio defines the speed ratio to apply (1 by default)
  79323. * @param onAnimationEnd defines a callback which will be called when animation will end
  79324. * @returns a new animatable
  79325. */
  79326. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  79327. var range = this.getAnimationRange(name);
  79328. if (!range) {
  79329. return null;
  79330. }
  79331. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  79332. };
  79333. /** @hidden */
  79334. Skeleton.prototype._markAsDirty = function () {
  79335. this._isDirty = true;
  79336. };
  79337. /** @hidden */
  79338. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  79339. this._meshesWithPoseMatrix.push(mesh);
  79340. };
  79341. /** @hidden */
  79342. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  79343. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  79344. if (index > -1) {
  79345. this._meshesWithPoseMatrix.splice(index, 1);
  79346. }
  79347. };
  79348. /** @hidden */
  79349. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  79350. this.onBeforeComputeObservable.notifyObservers(this);
  79351. for (var index = 0; index < this.bones.length; index++) {
  79352. var bone = this.bones[index];
  79353. var parentBone = bone.getParent();
  79354. if (parentBone) {
  79355. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  79356. }
  79357. else {
  79358. if (initialSkinMatrix) {
  79359. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  79360. }
  79361. else {
  79362. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  79363. }
  79364. }
  79365. if (bone._index !== -1) {
  79366. var mappedIndex = bone._index === null ? index : bone._index;
  79367. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  79368. }
  79369. }
  79370. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  79371. };
  79372. /**
  79373. * Build all resources required to render a skeleton
  79374. */
  79375. Skeleton.prototype.prepare = function () {
  79376. if (!this._isDirty) {
  79377. return;
  79378. }
  79379. if (this.needInitialSkinMatrix) {
  79380. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  79381. var mesh = this._meshesWithPoseMatrix[index];
  79382. var poseMatrix = mesh.getPoseMatrix();
  79383. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  79384. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  79385. }
  79386. if (this._synchronizedWithMesh !== mesh) {
  79387. this._synchronizedWithMesh = mesh;
  79388. // Prepare bones
  79389. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  79390. var bone = this.bones[boneIndex];
  79391. if (!bone.getParent()) {
  79392. var matrix = bone.getBaseMatrix();
  79393. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  79394. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  79395. }
  79396. }
  79397. }
  79398. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  79399. }
  79400. }
  79401. else {
  79402. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  79403. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  79404. }
  79405. this._computeTransformMatrices(this._transformMatrices, null);
  79406. }
  79407. this._isDirty = false;
  79408. this._scene._activeBones.addCount(this.bones.length, false);
  79409. };
  79410. /**
  79411. * Gets the list of animatables currently running for this skeleton
  79412. * @returns an array of animatables
  79413. */
  79414. Skeleton.prototype.getAnimatables = function () {
  79415. if (!this._animatables || this._animatables.length !== this.bones.length) {
  79416. this._animatables = [];
  79417. for (var index = 0; index < this.bones.length; index++) {
  79418. this._animatables.push(this.bones[index]);
  79419. }
  79420. }
  79421. return this._animatables;
  79422. };
  79423. /**
  79424. * Clone the current skeleton
  79425. * @param name defines the name of the new skeleton
  79426. * @param id defines the id of the enw skeleton
  79427. * @returns the new skeleton
  79428. */
  79429. Skeleton.prototype.clone = function (name, id) {
  79430. var result = new Skeleton(name, id || name, this._scene);
  79431. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  79432. for (var index = 0; index < this.bones.length; index++) {
  79433. var source = this.bones[index];
  79434. var parentBone = null;
  79435. var parent_1 = source.getParent();
  79436. if (parent_1) {
  79437. var parentIndex = this.bones.indexOf(parent_1);
  79438. parentBone = result.bones[parentIndex];
  79439. }
  79440. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  79441. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  79442. }
  79443. if (this._ranges) {
  79444. result._ranges = {};
  79445. for (var rangeName in this._ranges) {
  79446. var range = this._ranges[rangeName];
  79447. if (range) {
  79448. result._ranges[rangeName] = range.clone();
  79449. }
  79450. }
  79451. }
  79452. this._isDirty = true;
  79453. return result;
  79454. };
  79455. /**
  79456. * Enable animation blending for this skeleton
  79457. * @param blendingSpeed defines the blending speed to apply
  79458. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  79459. */
  79460. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  79461. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  79462. this.bones.forEach(function (bone) {
  79463. bone.animations.forEach(function (animation) {
  79464. animation.enableBlending = true;
  79465. animation.blendingSpeed = blendingSpeed;
  79466. });
  79467. });
  79468. };
  79469. /**
  79470. * Releases all resources associated with the current skeleton
  79471. */
  79472. Skeleton.prototype.dispose = function () {
  79473. this._meshesWithPoseMatrix = [];
  79474. // Animations
  79475. this.getScene().stopAnimation(this);
  79476. // Remove from scene
  79477. this.getScene().removeSkeleton(this);
  79478. };
  79479. /**
  79480. * Serialize the skeleton in a JSON object
  79481. * @returns a JSON object
  79482. */
  79483. Skeleton.prototype.serialize = function () {
  79484. var serializationObject = {};
  79485. serializationObject.name = this.name;
  79486. serializationObject.id = this.id;
  79487. if (this.dimensionsAtRest) {
  79488. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  79489. }
  79490. serializationObject.bones = [];
  79491. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  79492. for (var index = 0; index < this.bones.length; index++) {
  79493. var bone = this.bones[index];
  79494. var parent_2 = bone.getParent();
  79495. var serializedBone = {
  79496. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  79497. name: bone.name,
  79498. matrix: bone.getBaseMatrix().toArray(),
  79499. rest: bone.getRestPose().toArray()
  79500. };
  79501. serializationObject.bones.push(serializedBone);
  79502. if (bone.length) {
  79503. serializedBone.length = bone.length;
  79504. }
  79505. if (bone.metadata) {
  79506. serializedBone.metadata = bone.metadata;
  79507. }
  79508. if (bone.animations && bone.animations.length > 0) {
  79509. serializedBone.animation = bone.animations[0].serialize();
  79510. }
  79511. serializationObject.ranges = [];
  79512. for (var name in this._ranges) {
  79513. var source = this._ranges[name];
  79514. if (!source) {
  79515. continue;
  79516. }
  79517. var range = {};
  79518. range.name = name;
  79519. range.from = source.from;
  79520. range.to = source.to;
  79521. serializationObject.ranges.push(range);
  79522. }
  79523. }
  79524. return serializationObject;
  79525. };
  79526. /**
  79527. * Creates a new skeleton from serialized data
  79528. * @param parsedSkeleton defines the serialized data
  79529. * @param scene defines the hosting scene
  79530. * @returns a new skeleton
  79531. */
  79532. Skeleton.Parse = function (parsedSkeleton, scene) {
  79533. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  79534. if (parsedSkeleton.dimensionsAtRest) {
  79535. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  79536. }
  79537. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  79538. var index;
  79539. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  79540. var parsedBone = parsedSkeleton.bones[index];
  79541. var parentBone = null;
  79542. if (parsedBone.parentBoneIndex > -1) {
  79543. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  79544. }
  79545. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  79546. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  79547. if (parsedBone.length) {
  79548. bone.length = parsedBone.length;
  79549. }
  79550. if (parsedBone.metadata) {
  79551. bone.metadata = parsedBone.metadata;
  79552. }
  79553. if (parsedBone.animation) {
  79554. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  79555. }
  79556. }
  79557. // placed after bones, so createAnimationRange can cascade down
  79558. if (parsedSkeleton.ranges) {
  79559. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  79560. var data = parsedSkeleton.ranges[index];
  79561. skeleton.createAnimationRange(data.name, data.from, data.to);
  79562. }
  79563. }
  79564. return skeleton;
  79565. };
  79566. /**
  79567. * Compute all node absolute transforms
  79568. * @param forceUpdate defines if computation must be done even if cache is up to date
  79569. */
  79570. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  79571. if (forceUpdate === void 0) { forceUpdate = false; }
  79572. var renderId = this._scene.getRenderId();
  79573. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  79574. this.bones[0].computeAbsoluteTransforms();
  79575. this._lastAbsoluteTransformsUpdateId = renderId;
  79576. }
  79577. };
  79578. /**
  79579. * Gets the root pose matrix
  79580. * @returns a matrix
  79581. */
  79582. Skeleton.prototype.getPoseMatrix = function () {
  79583. var poseMatrix = null;
  79584. if (this._meshesWithPoseMatrix.length > 0) {
  79585. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  79586. }
  79587. return poseMatrix;
  79588. };
  79589. /**
  79590. * Sorts bones per internal index
  79591. */
  79592. Skeleton.prototype.sortBones = function () {
  79593. var bones = new Array();
  79594. var visited = new Array(this.bones.length);
  79595. for (var index = 0; index < this.bones.length; index++) {
  79596. this._sortBones(index, bones, visited);
  79597. }
  79598. this.bones = bones;
  79599. };
  79600. Skeleton.prototype._sortBones = function (index, bones, visited) {
  79601. if (visited[index]) {
  79602. return;
  79603. }
  79604. visited[index] = true;
  79605. var bone = this.bones[index];
  79606. if (bone._index === undefined) {
  79607. bone._index = index;
  79608. }
  79609. var parentBone = bone.getParent();
  79610. if (parentBone) {
  79611. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  79612. }
  79613. bones.push(bone);
  79614. };
  79615. return Skeleton;
  79616. }());
  79617. BABYLON.Skeleton = Skeleton;
  79618. })(BABYLON || (BABYLON = {}));
  79619. //# sourceMappingURL=babylon.skeleton.js.map
  79620. var BABYLON;
  79621. (function (BABYLON) {
  79622. var SphericalPolynomial = /** @class */ (function () {
  79623. function SphericalPolynomial() {
  79624. this.x = BABYLON.Vector3.Zero();
  79625. this.y = BABYLON.Vector3.Zero();
  79626. this.z = BABYLON.Vector3.Zero();
  79627. this.xx = BABYLON.Vector3.Zero();
  79628. this.yy = BABYLON.Vector3.Zero();
  79629. this.zz = BABYLON.Vector3.Zero();
  79630. this.xy = BABYLON.Vector3.Zero();
  79631. this.yz = BABYLON.Vector3.Zero();
  79632. this.zx = BABYLON.Vector3.Zero();
  79633. }
  79634. SphericalPolynomial.prototype.addAmbient = function (color) {
  79635. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  79636. this.xx = this.xx.add(colorVector);
  79637. this.yy = this.yy.add(colorVector);
  79638. this.zz = this.zz.add(colorVector);
  79639. };
  79640. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  79641. var result = new SphericalPolynomial();
  79642. result.x = harmonics.L11.scale(1.02333);
  79643. result.y = harmonics.L1_1.scale(1.02333);
  79644. result.z = harmonics.L10.scale(1.02333);
  79645. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  79646. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  79647. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  79648. result.yz = harmonics.L2_1.scale(0.858086);
  79649. result.zx = harmonics.L21.scale(0.858086);
  79650. result.xy = harmonics.L2_2.scale(0.858086);
  79651. result.scale(1.0 / Math.PI);
  79652. return result;
  79653. };
  79654. SphericalPolynomial.prototype.scale = function (scale) {
  79655. this.x = this.x.scale(scale);
  79656. this.y = this.y.scale(scale);
  79657. this.z = this.z.scale(scale);
  79658. this.xx = this.xx.scale(scale);
  79659. this.yy = this.yy.scale(scale);
  79660. this.zz = this.zz.scale(scale);
  79661. this.yz = this.yz.scale(scale);
  79662. this.zx = this.zx.scale(scale);
  79663. this.xy = this.xy.scale(scale);
  79664. };
  79665. return SphericalPolynomial;
  79666. }());
  79667. BABYLON.SphericalPolynomial = SphericalPolynomial;
  79668. var SphericalHarmonics = /** @class */ (function () {
  79669. function SphericalHarmonics() {
  79670. this.L00 = BABYLON.Vector3.Zero();
  79671. this.L1_1 = BABYLON.Vector3.Zero();
  79672. this.L10 = BABYLON.Vector3.Zero();
  79673. this.L11 = BABYLON.Vector3.Zero();
  79674. this.L2_2 = BABYLON.Vector3.Zero();
  79675. this.L2_1 = BABYLON.Vector3.Zero();
  79676. this.L20 = BABYLON.Vector3.Zero();
  79677. this.L21 = BABYLON.Vector3.Zero();
  79678. this.L22 = BABYLON.Vector3.Zero();
  79679. }
  79680. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  79681. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  79682. var c = colorVector.scale(deltaSolidAngle);
  79683. this.L00 = this.L00.add(c.scale(0.282095));
  79684. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  79685. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  79686. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  79687. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  79688. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  79689. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  79690. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  79691. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  79692. };
  79693. SphericalHarmonics.prototype.scale = function (scale) {
  79694. this.L00 = this.L00.scale(scale);
  79695. this.L1_1 = this.L1_1.scale(scale);
  79696. this.L10 = this.L10.scale(scale);
  79697. this.L11 = this.L11.scale(scale);
  79698. this.L2_2 = this.L2_2.scale(scale);
  79699. this.L2_1 = this.L2_1.scale(scale);
  79700. this.L20 = this.L20.scale(scale);
  79701. this.L21 = this.L21.scale(scale);
  79702. this.L22 = this.L22.scale(scale);
  79703. };
  79704. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  79705. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  79706. //
  79707. // E_lm = A_l * L_lm
  79708. //
  79709. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  79710. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  79711. // the scaling factors are given in equation 9.
  79712. // Constant (Band 0)
  79713. this.L00 = this.L00.scale(3.141593);
  79714. // Linear (Band 1)
  79715. this.L1_1 = this.L1_1.scale(2.094395);
  79716. this.L10 = this.L10.scale(2.094395);
  79717. this.L11 = this.L11.scale(2.094395);
  79718. // Quadratic (Band 2)
  79719. this.L2_2 = this.L2_2.scale(0.785398);
  79720. this.L2_1 = this.L2_1.scale(0.785398);
  79721. this.L20 = this.L20.scale(0.785398);
  79722. this.L21 = this.L21.scale(0.785398);
  79723. this.L22 = this.L22.scale(0.785398);
  79724. };
  79725. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  79726. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  79727. // L = (1/pi) * E * rho
  79728. //
  79729. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  79730. this.scale(1.0 / Math.PI);
  79731. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  79732. // (The pixel shader must apply albedo after texture fetches, etc).
  79733. };
  79734. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  79735. var result = new SphericalHarmonics();
  79736. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  79737. result.L1_1 = polynomial.y.scale(0.977204);
  79738. result.L10 = polynomial.z.scale(0.977204);
  79739. result.L11 = polynomial.x.scale(0.977204);
  79740. result.L2_2 = polynomial.xy.scale(1.16538);
  79741. result.L2_1 = polynomial.yz.scale(1.16538);
  79742. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  79743. result.L21 = polynomial.zx.scale(1.16538);
  79744. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  79745. result.scale(Math.PI);
  79746. return result;
  79747. };
  79748. return SphericalHarmonics;
  79749. }());
  79750. BABYLON.SphericalHarmonics = SphericalHarmonics;
  79751. })(BABYLON || (BABYLON = {}));
  79752. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  79753. var BABYLON;
  79754. (function (BABYLON) {
  79755. var FileFaceOrientation = /** @class */ (function () {
  79756. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  79757. this.name = name;
  79758. this.worldAxisForNormal = worldAxisForNormal;
  79759. this.worldAxisForFileX = worldAxisForFileX;
  79760. this.worldAxisForFileY = worldAxisForFileY;
  79761. }
  79762. return FileFaceOrientation;
  79763. }());
  79764. ;
  79765. /**
  79766. * Helper class dealing with the extraction of spherical polynomial dataArray
  79767. * from a cube map.
  79768. */
  79769. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  79770. function CubeMapToSphericalPolynomialTools() {
  79771. }
  79772. /**
  79773. * Converts a texture to the according Spherical Polynomial data.
  79774. * This extracts the first 3 orders only as they are the only one used in the lighting.
  79775. *
  79776. * @param texture The texture to extract the information from.
  79777. * @return The Spherical Polynomial data.
  79778. */
  79779. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  79780. if (!texture.isCube) {
  79781. // Only supports cube Textures currently.
  79782. return null;
  79783. }
  79784. var size = texture.getSize().width;
  79785. var right = texture.readPixels(0);
  79786. var left = texture.readPixels(1);
  79787. var up;
  79788. var down;
  79789. if (texture.isRenderTarget) {
  79790. up = texture.readPixels(3);
  79791. down = texture.readPixels(2);
  79792. }
  79793. else {
  79794. up = texture.readPixels(2);
  79795. down = texture.readPixels(3);
  79796. }
  79797. var front = texture.readPixels(4);
  79798. var back = texture.readPixels(5);
  79799. var gammaSpace = texture.gammaSpace;
  79800. // Always read as RGBA.
  79801. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  79802. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  79803. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  79804. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  79805. }
  79806. var cubeInfo = {
  79807. size: size,
  79808. right: right,
  79809. left: left,
  79810. up: up,
  79811. down: down,
  79812. front: front,
  79813. back: back,
  79814. format: format,
  79815. type: type,
  79816. gammaSpace: gammaSpace,
  79817. };
  79818. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  79819. };
  79820. /**
  79821. * Converts a cubemap to the according Spherical Polynomial data.
  79822. * This extracts the first 3 orders only as they are the only one used in the lighting.
  79823. *
  79824. * @param cubeInfo The Cube map to extract the information from.
  79825. * @return The Spherical Polynomial data.
  79826. */
  79827. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  79828. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  79829. var totalSolidAngle = 0.0;
  79830. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  79831. var du = 2.0 / cubeInfo.size;
  79832. var dv = du;
  79833. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  79834. var minUV = du * 0.5 - 1.0;
  79835. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  79836. var fileFace = this.FileFaces[faceIndex];
  79837. var dataArray = cubeInfo[fileFace.name];
  79838. var v = minUV;
  79839. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  79840. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  79841. // Because SP is still linear, so summation is fine in that basis.
  79842. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  79843. for (var y = 0; y < cubeInfo.size; y++) {
  79844. var u = minUV;
  79845. for (var x = 0; x < cubeInfo.size; x++) {
  79846. // World direction (not normalised)
  79847. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  79848. worldDirection.normalize();
  79849. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  79850. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  79851. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  79852. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  79853. // Handle Integer types.
  79854. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  79855. r /= 255;
  79856. g /= 255;
  79857. b /= 255;
  79858. }
  79859. // Handle Gamma space textures.
  79860. if (cubeInfo.gammaSpace) {
  79861. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  79862. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  79863. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  79864. }
  79865. var color = new BABYLON.Color3(r, g, b);
  79866. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  79867. totalSolidAngle += deltaSolidAngle;
  79868. u += du;
  79869. }
  79870. v += dv;
  79871. }
  79872. }
  79873. // Solid angle for entire sphere is 4*pi
  79874. var sphereSolidAngle = 4.0 * Math.PI;
  79875. // Adjust the solid angle to allow for how many faces we processed.
  79876. var facesProcessed = 6.0;
  79877. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  79878. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  79879. // This is needed because the numerical integration over the cube uses a
  79880. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  79881. // and also to compensate for accumulative error due to float precision in the summation.
  79882. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  79883. sphericalHarmonics.scale(correctionFactor);
  79884. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  79885. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  79886. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  79887. };
  79888. CubeMapToSphericalPolynomialTools.FileFaces = [
  79889. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  79890. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  79891. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  79892. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  79893. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  79894. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  79895. ];
  79896. return CubeMapToSphericalPolynomialTools;
  79897. }());
  79898. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  79899. })(BABYLON || (BABYLON = {}));
  79900. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  79901. var BABYLON;
  79902. (function (BABYLON) {
  79903. /**
  79904. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  79905. */
  79906. var PanoramaToCubeMapTools = /** @class */ (function () {
  79907. function PanoramaToCubeMapTools() {
  79908. }
  79909. /**
  79910. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  79911. *
  79912. * @param float32Array The source data.
  79913. * @param inputWidth The width of the input panorama.
  79914. * @param inputhHeight The height of the input panorama.
  79915. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  79916. * @return The cubemap data
  79917. */
  79918. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  79919. if (!float32Array) {
  79920. throw "ConvertPanoramaToCubemap: input cannot be null";
  79921. }
  79922. if (float32Array.length != inputWidth * inputHeight * 3) {
  79923. throw "ConvertPanoramaToCubemap: input size is wrong";
  79924. }
  79925. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  79926. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  79927. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  79928. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  79929. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  79930. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  79931. return {
  79932. front: textureFront,
  79933. back: textureBack,
  79934. left: textureLeft,
  79935. right: textureRight,
  79936. up: textureUp,
  79937. down: textureDown,
  79938. size: size,
  79939. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  79940. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  79941. gammaSpace: false,
  79942. };
  79943. };
  79944. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  79945. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  79946. var textureArray = new Float32Array(buffer);
  79947. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  79948. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  79949. var dy = 1 / texSize;
  79950. var fy = 0;
  79951. for (var y = 0; y < texSize; y++) {
  79952. var xv1 = faceData[0];
  79953. var xv2 = faceData[2];
  79954. for (var x = 0; x < texSize; x++) {
  79955. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  79956. v.normalize();
  79957. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  79958. // 3 channels per pixels
  79959. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  79960. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  79961. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  79962. xv1 = xv1.add(rotDX1);
  79963. xv2 = xv2.add(rotDX2);
  79964. }
  79965. fy += dy;
  79966. }
  79967. return textureArray;
  79968. };
  79969. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  79970. var theta = Math.atan2(vDir.z, vDir.x);
  79971. var phi = Math.acos(vDir.y);
  79972. while (theta < -Math.PI)
  79973. theta += 2 * Math.PI;
  79974. while (theta > Math.PI)
  79975. theta -= 2 * Math.PI;
  79976. var dx = theta / Math.PI;
  79977. var dy = phi / Math.PI;
  79978. // recenter.
  79979. dx = dx * 0.5 + 0.5;
  79980. var px = Math.round(dx * inputWidth);
  79981. if (px < 0)
  79982. px = 0;
  79983. else if (px >= inputWidth)
  79984. px = inputWidth - 1;
  79985. var py = Math.round(dy * inputHeight);
  79986. if (py < 0)
  79987. py = 0;
  79988. else if (py >= inputHeight)
  79989. py = inputHeight - 1;
  79990. var inputY = (inputHeight - py - 1);
  79991. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  79992. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  79993. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  79994. return {
  79995. r: r,
  79996. g: g,
  79997. b: b
  79998. };
  79999. };
  80000. PanoramaToCubeMapTools.FACE_FRONT = [
  80001. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  80002. new BABYLON.Vector3(1.0, -1.0, -1.0),
  80003. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  80004. new BABYLON.Vector3(1.0, 1.0, -1.0)
  80005. ];
  80006. PanoramaToCubeMapTools.FACE_BACK = [
  80007. new BABYLON.Vector3(1.0, -1.0, 1.0),
  80008. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  80009. new BABYLON.Vector3(1.0, 1.0, 1.0),
  80010. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  80011. ];
  80012. PanoramaToCubeMapTools.FACE_RIGHT = [
  80013. new BABYLON.Vector3(1.0, -1.0, -1.0),
  80014. new BABYLON.Vector3(1.0, -1.0, 1.0),
  80015. new BABYLON.Vector3(1.0, 1.0, -1.0),
  80016. new BABYLON.Vector3(1.0, 1.0, 1.0)
  80017. ];
  80018. PanoramaToCubeMapTools.FACE_LEFT = [
  80019. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  80020. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  80021. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  80022. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  80023. ];
  80024. PanoramaToCubeMapTools.FACE_DOWN = [
  80025. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  80026. new BABYLON.Vector3(1.0, 1.0, -1.0),
  80027. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  80028. new BABYLON.Vector3(1.0, 1.0, 1.0)
  80029. ];
  80030. PanoramaToCubeMapTools.FACE_UP = [
  80031. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  80032. new BABYLON.Vector3(1.0, -1.0, 1.0),
  80033. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  80034. new BABYLON.Vector3(1.0, -1.0, -1.0)
  80035. ];
  80036. return PanoramaToCubeMapTools;
  80037. }());
  80038. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  80039. })(BABYLON || (BABYLON = {}));
  80040. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  80041. var BABYLON;
  80042. (function (BABYLON) {
  80043. ;
  80044. /**
  80045. * This groups tools to convert HDR texture to native colors array.
  80046. */
  80047. var HDRTools = /** @class */ (function () {
  80048. function HDRTools() {
  80049. }
  80050. HDRTools.Ldexp = function (mantissa, exponent) {
  80051. if (exponent > 1023) {
  80052. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  80053. }
  80054. if (exponent < -1074) {
  80055. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  80056. }
  80057. return mantissa * Math.pow(2, exponent);
  80058. };
  80059. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  80060. if (exponent > 0) { /*nonzero pixel*/
  80061. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  80062. float32array[index + 0] = red * exponent;
  80063. float32array[index + 1] = green * exponent;
  80064. float32array[index + 2] = blue * exponent;
  80065. }
  80066. else {
  80067. float32array[index + 0] = 0;
  80068. float32array[index + 1] = 0;
  80069. float32array[index + 2] = 0;
  80070. }
  80071. };
  80072. HDRTools.readStringLine = function (uint8array, startIndex) {
  80073. var line = "";
  80074. var character = "";
  80075. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  80076. character = String.fromCharCode(uint8array[i]);
  80077. if (character == "\n") {
  80078. break;
  80079. }
  80080. line += character;
  80081. }
  80082. return line;
  80083. };
  80084. /**
  80085. * Reads header information from an RGBE texture stored in a native array.
  80086. * More information on this format are available here:
  80087. * https://en.wikipedia.org/wiki/RGBE_image_format
  80088. *
  80089. * @param uint8array The binary file stored in native array.
  80090. * @return The header information.
  80091. */
  80092. HDRTools.RGBE_ReadHeader = function (uint8array) {
  80093. var height = 0;
  80094. var width = 0;
  80095. var line = this.readStringLine(uint8array, 0);
  80096. if (line[0] != '#' || line[1] != '?') {
  80097. throw "Bad HDR Format.";
  80098. }
  80099. var endOfHeader = false;
  80100. var findFormat = false;
  80101. var lineIndex = 0;
  80102. do {
  80103. lineIndex += (line.length + 1);
  80104. line = this.readStringLine(uint8array, lineIndex);
  80105. if (line == "FORMAT=32-bit_rle_rgbe") {
  80106. findFormat = true;
  80107. }
  80108. else if (line.length == 0) {
  80109. endOfHeader = true;
  80110. }
  80111. } while (!endOfHeader);
  80112. if (!findFormat) {
  80113. throw "HDR Bad header format, unsupported FORMAT";
  80114. }
  80115. lineIndex += (line.length + 1);
  80116. line = this.readStringLine(uint8array, lineIndex);
  80117. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  80118. var match = sizeRegexp.exec(line);
  80119. // TODO. Support +Y and -X if needed.
  80120. if (!match || match.length < 3) {
  80121. throw "HDR Bad header format, no size";
  80122. }
  80123. width = parseInt(match[2]);
  80124. height = parseInt(match[1]);
  80125. if (width < 8 || width > 0x7fff) {
  80126. throw "HDR Bad header format, unsupported size";
  80127. }
  80128. lineIndex += (line.length + 1);
  80129. return {
  80130. height: height,
  80131. width: width,
  80132. dataPosition: lineIndex
  80133. };
  80134. };
  80135. /**
  80136. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  80137. * This RGBE texture needs to store the information as a panorama.
  80138. *
  80139. * More information on this format are available here:
  80140. * https://en.wikipedia.org/wiki/RGBE_image_format
  80141. *
  80142. * @param buffer The binary file stored in an array buffer.
  80143. * @param size The expected size of the extracted cubemap.
  80144. * @return The Cube Map information.
  80145. */
  80146. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  80147. var uint8array = new Uint8Array(buffer);
  80148. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  80149. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  80150. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  80151. return cubeMapData;
  80152. };
  80153. /**
  80154. * Returns the pixels data extracted from an RGBE texture.
  80155. * This pixels will be stored left to right up to down in the R G B order in one array.
  80156. *
  80157. * More information on this format are available here:
  80158. * https://en.wikipedia.org/wiki/RGBE_image_format
  80159. *
  80160. * @param uint8array The binary file stored in an array buffer.
  80161. * @param hdrInfo The header information of the file.
  80162. * @return The pixels data in RGB right to left up to down order.
  80163. */
  80164. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  80165. // Keep for multi format supports.
  80166. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  80167. };
  80168. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  80169. var num_scanlines = hdrInfo.height;
  80170. var scanline_width = hdrInfo.width;
  80171. var a, b, c, d, count;
  80172. var dataIndex = hdrInfo.dataPosition;
  80173. var index = 0, endIndex = 0, i = 0;
  80174. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  80175. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  80176. // 3 channels of 4 bytes per pixel in float.
  80177. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  80178. var resultArray = new Float32Array(resultBuffer);
  80179. // read in each successive scanline
  80180. while (num_scanlines > 0) {
  80181. a = uint8array[dataIndex++];
  80182. b = uint8array[dataIndex++];
  80183. c = uint8array[dataIndex++];
  80184. d = uint8array[dataIndex++];
  80185. if (a != 2 || b != 2 || (c & 0x80)) {
  80186. // this file is not run length encoded
  80187. throw "HDR Bad header format, not RLE";
  80188. }
  80189. if (((c << 8) | d) != scanline_width) {
  80190. throw "HDR Bad header format, wrong scan line width";
  80191. }
  80192. index = 0;
  80193. // read each of the four channels for the scanline into the buffer
  80194. for (i = 0; i < 4; i++) {
  80195. endIndex = (i + 1) * scanline_width;
  80196. while (index < endIndex) {
  80197. a = uint8array[dataIndex++];
  80198. b = uint8array[dataIndex++];
  80199. if (a > 128) {
  80200. // a run of the same value
  80201. count = a - 128;
  80202. if ((count == 0) || (count > endIndex - index)) {
  80203. throw "HDR Bad Format, bad scanline data (run)";
  80204. }
  80205. while (count-- > 0) {
  80206. scanLineArray[index++] = b;
  80207. }
  80208. }
  80209. else {
  80210. // a non-run
  80211. count = a;
  80212. if ((count == 0) || (count > endIndex - index)) {
  80213. throw "HDR Bad Format, bad scanline data (non-run)";
  80214. }
  80215. scanLineArray[index++] = b;
  80216. if (--count > 0) {
  80217. for (var j = 0; j < count; j++) {
  80218. scanLineArray[index++] = uint8array[dataIndex++];
  80219. }
  80220. }
  80221. }
  80222. }
  80223. }
  80224. // now convert data from buffer into floats
  80225. for (i = 0; i < scanline_width; i++) {
  80226. a = scanLineArray[i];
  80227. b = scanLineArray[i + scanline_width];
  80228. c = scanLineArray[i + 2 * scanline_width];
  80229. d = scanLineArray[i + 3 * scanline_width];
  80230. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  80231. }
  80232. num_scanlines--;
  80233. }
  80234. return resultArray;
  80235. };
  80236. return HDRTools;
  80237. }());
  80238. BABYLON.HDRTools = HDRTools;
  80239. })(BABYLON || (BABYLON = {}));
  80240. //# sourceMappingURL=babylon.hdr.js.map
  80241. var BABYLON;
  80242. (function (BABYLON) {
  80243. /**
  80244. * This represents a texture coming from an HDR input.
  80245. *
  80246. * The only supported format is currently panorama picture stored in RGBE format.
  80247. * Example of such files can be found on HDRLib: http://hdrlib.com/
  80248. */
  80249. var HDRCubeTexture = /** @class */ (function (_super) {
  80250. __extends(HDRCubeTexture, _super);
  80251. /**
  80252. * Instantiates an HDRTexture from the following parameters.
  80253. *
  80254. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  80255. * @param scene The scene the texture will be used in
  80256. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  80257. * @param noMipmap Forces to not generate the mipmap if true
  80258. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  80259. * @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)
  80260. * @param reserved Reserved flag for internal use.
  80261. */
  80262. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  80263. if (noMipmap === void 0) { noMipmap = false; }
  80264. if (generateHarmonics === void 0) { generateHarmonics = true; }
  80265. if (gammaSpace === void 0) { gammaSpace = false; }
  80266. if (reserved === void 0) { reserved = false; }
  80267. if (onLoad === void 0) { onLoad = null; }
  80268. if (onError === void 0) { onError = null; }
  80269. var _this = _super.call(this, scene) || this;
  80270. _this._generateHarmonics = true;
  80271. _this._onLoad = null;
  80272. _this._onError = null;
  80273. /**
  80274. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  80275. */
  80276. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  80277. _this._isBlocking = true;
  80278. _this._rotationY = 0;
  80279. /**
  80280. * Gets or sets the center of the bounding box associated with the cube texture
  80281. * It must define where the camera used to render the texture was set
  80282. */
  80283. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  80284. if (!url) {
  80285. return _this;
  80286. }
  80287. _this.name = url;
  80288. _this.url = url;
  80289. _this.hasAlpha = false;
  80290. _this.isCube = true;
  80291. _this._textureMatrix = BABYLON.Matrix.Identity();
  80292. _this._onLoad = onLoad;
  80293. _this._onError = onError;
  80294. _this.gammaSpace = gammaSpace;
  80295. _this._noMipmap = noMipmap;
  80296. _this._size = size;
  80297. _this._texture = _this._getFromCache(url, _this._noMipmap);
  80298. if (!_this._texture) {
  80299. if (!scene.useDelayedTextureLoading) {
  80300. _this.loadTexture();
  80301. }
  80302. else {
  80303. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  80304. }
  80305. }
  80306. return _this;
  80307. }
  80308. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  80309. /**
  80310. * Gets wether or not the texture is blocking during loading.
  80311. */
  80312. get: function () {
  80313. return this._isBlocking;
  80314. },
  80315. /**
  80316. * Sets wether or not the texture is blocking during loading.
  80317. */
  80318. set: function (value) {
  80319. this._isBlocking = value;
  80320. },
  80321. enumerable: true,
  80322. configurable: true
  80323. });
  80324. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  80325. /**
  80326. * Gets texture matrix rotation angle around Y axis radians.
  80327. */
  80328. get: function () {
  80329. return this._rotationY;
  80330. },
  80331. /**
  80332. * Sets texture matrix rotation angle around Y axis in radians.
  80333. */
  80334. set: function (value) {
  80335. this._rotationY = value;
  80336. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  80337. },
  80338. enumerable: true,
  80339. configurable: true
  80340. });
  80341. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  80342. get: function () {
  80343. return this._boundingBoxSize;
  80344. },
  80345. /**
  80346. * Gets or sets the size of the bounding box associated with the cube texture
  80347. * When defined, the cubemap will switch to local mode
  80348. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  80349. * @example https://www.babylonjs-playground.com/#RNASML
  80350. */
  80351. set: function (value) {
  80352. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  80353. return;
  80354. }
  80355. this._boundingBoxSize = value;
  80356. var scene = this.getScene();
  80357. if (scene) {
  80358. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  80359. }
  80360. },
  80361. enumerable: true,
  80362. configurable: true
  80363. });
  80364. /**
  80365. * Occurs when the file is raw .hdr file.
  80366. */
  80367. HDRCubeTexture.prototype.loadTexture = function () {
  80368. var _this = this;
  80369. var callback = function (buffer) {
  80370. var scene = _this.getScene();
  80371. if (!scene) {
  80372. return null;
  80373. }
  80374. // Extract the raw linear data.
  80375. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  80376. // Generate harmonics if needed.
  80377. if (_this._generateHarmonics) {
  80378. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  80379. _this.sphericalPolynomial = sphericalPolynomial;
  80380. }
  80381. var results = [];
  80382. var byteArray = null;
  80383. // Push each faces.
  80384. for (var j = 0; j < 6; j++) {
  80385. // Create uintarray fallback.
  80386. if (!scene.getEngine().getCaps().textureFloat) {
  80387. // 3 channels of 1 bytes per pixel in bytes.
  80388. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  80389. byteArray = new Uint8Array(byteBuffer);
  80390. }
  80391. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  80392. // If special cases.
  80393. if (_this.gammaSpace || byteArray) {
  80394. for (var i = 0; i < _this._size * _this._size; i++) {
  80395. // Put in gamma space if requested.
  80396. if (_this.gammaSpace) {
  80397. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  80398. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  80399. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  80400. }
  80401. // Convert to int texture for fallback.
  80402. if (byteArray) {
  80403. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  80404. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  80405. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  80406. // May use luminance instead if the result is not accurate.
  80407. var max = Math.max(Math.max(r, g), b);
  80408. if (max > 255) {
  80409. var scale = 255 / max;
  80410. r *= scale;
  80411. g *= scale;
  80412. b *= scale;
  80413. }
  80414. byteArray[(i * 3) + 0] = r;
  80415. byteArray[(i * 3) + 1] = g;
  80416. byteArray[(i * 3) + 2] = b;
  80417. }
  80418. }
  80419. }
  80420. if (byteArray) {
  80421. results.push(byteArray);
  80422. }
  80423. else {
  80424. results.push(dataFace);
  80425. }
  80426. }
  80427. return results;
  80428. };
  80429. var scene = this.getScene();
  80430. if (scene) {
  80431. 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);
  80432. }
  80433. };
  80434. HDRCubeTexture.prototype.clone = function () {
  80435. var scene = this.getScene();
  80436. if (!scene) {
  80437. return this;
  80438. }
  80439. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  80440. // Base texture
  80441. newTexture.level = this.level;
  80442. newTexture.wrapU = this.wrapU;
  80443. newTexture.wrapV = this.wrapV;
  80444. newTexture.coordinatesIndex = this.coordinatesIndex;
  80445. newTexture.coordinatesMode = this.coordinatesMode;
  80446. return newTexture;
  80447. };
  80448. // Methods
  80449. HDRCubeTexture.prototype.delayLoad = function () {
  80450. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  80451. return;
  80452. }
  80453. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  80454. this._texture = this._getFromCache(this.url, this._noMipmap);
  80455. if (!this._texture) {
  80456. this.loadTexture();
  80457. }
  80458. };
  80459. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  80460. return this._textureMatrix;
  80461. };
  80462. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  80463. this._textureMatrix = value;
  80464. };
  80465. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  80466. var texture = null;
  80467. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  80468. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  80469. texture.name = parsedTexture.name;
  80470. texture.hasAlpha = parsedTexture.hasAlpha;
  80471. texture.level = parsedTexture.level;
  80472. texture.coordinatesMode = parsedTexture.coordinatesMode;
  80473. texture.isBlocking = parsedTexture.isBlocking;
  80474. }
  80475. if (texture) {
  80476. if (parsedTexture.boundingBoxPosition) {
  80477. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  80478. }
  80479. if (parsedTexture.boundingBoxSize) {
  80480. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  80481. }
  80482. if (parsedTexture.rotationY) {
  80483. texture.rotationY = parsedTexture.rotationY;
  80484. }
  80485. }
  80486. return texture;
  80487. };
  80488. HDRCubeTexture.prototype.serialize = function () {
  80489. if (!this.name) {
  80490. return null;
  80491. }
  80492. var serializationObject = {};
  80493. serializationObject.name = this.name;
  80494. serializationObject.hasAlpha = this.hasAlpha;
  80495. serializationObject.isCube = true;
  80496. serializationObject.level = this.level;
  80497. serializationObject.size = this._size;
  80498. serializationObject.coordinatesMode = this.coordinatesMode;
  80499. serializationObject.useInGammaSpace = this.gammaSpace;
  80500. serializationObject.generateHarmonics = this._generateHarmonics;
  80501. serializationObject.customType = "BABYLON.HDRCubeTexture";
  80502. serializationObject.noMipmap = this._noMipmap;
  80503. serializationObject.isBlocking = this._isBlocking;
  80504. serializationObject.rotationY = this._rotationY;
  80505. return serializationObject;
  80506. };
  80507. HDRCubeTexture._facesMapping = [
  80508. "right",
  80509. "left",
  80510. "up",
  80511. "down",
  80512. "front",
  80513. "back"
  80514. ];
  80515. return HDRCubeTexture;
  80516. }(BABYLON.BaseTexture));
  80517. BABYLON.HDRCubeTexture = HDRCubeTexture;
  80518. })(BABYLON || (BABYLON = {}));
  80519. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  80520. var BABYLON;
  80521. (function (BABYLON) {
  80522. var IndexedVector2 = /** @class */ (function (_super) {
  80523. __extends(IndexedVector2, _super);
  80524. function IndexedVector2(original, index) {
  80525. var _this = _super.call(this, original.x, original.y) || this;
  80526. _this.index = index;
  80527. return _this;
  80528. }
  80529. return IndexedVector2;
  80530. }(BABYLON.Vector2));
  80531. var PolygonPoints = /** @class */ (function () {
  80532. function PolygonPoints() {
  80533. this.elements = new Array();
  80534. }
  80535. PolygonPoints.prototype.add = function (originalPoints) {
  80536. var _this = this;
  80537. var result = new Array();
  80538. originalPoints.forEach(function (point) {
  80539. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  80540. var newPoint = new IndexedVector2(point, _this.elements.length);
  80541. result.push(newPoint);
  80542. _this.elements.push(newPoint);
  80543. }
  80544. });
  80545. return result;
  80546. };
  80547. PolygonPoints.prototype.computeBounds = function () {
  80548. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  80549. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  80550. this.elements.forEach(function (point) {
  80551. // x
  80552. if (point.x < lmin.x) {
  80553. lmin.x = point.x;
  80554. }
  80555. else if (point.x > lmax.x) {
  80556. lmax.x = point.x;
  80557. }
  80558. // y
  80559. if (point.y < lmin.y) {
  80560. lmin.y = point.y;
  80561. }
  80562. else if (point.y > lmax.y) {
  80563. lmax.y = point.y;
  80564. }
  80565. });
  80566. return {
  80567. min: lmin,
  80568. max: lmax,
  80569. width: lmax.x - lmin.x,
  80570. height: lmax.y - lmin.y
  80571. };
  80572. };
  80573. return PolygonPoints;
  80574. }());
  80575. var Polygon = /** @class */ (function () {
  80576. function Polygon() {
  80577. }
  80578. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  80579. return [
  80580. new BABYLON.Vector2(xmin, ymin),
  80581. new BABYLON.Vector2(xmax, ymin),
  80582. new BABYLON.Vector2(xmax, ymax),
  80583. new BABYLON.Vector2(xmin, ymax)
  80584. ];
  80585. };
  80586. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  80587. if (cx === void 0) { cx = 0; }
  80588. if (cy === void 0) { cy = 0; }
  80589. if (numberOfSides === void 0) { numberOfSides = 32; }
  80590. var result = new Array();
  80591. var angle = 0;
  80592. var increment = (Math.PI * 2) / numberOfSides;
  80593. for (var i = 0; i < numberOfSides; i++) {
  80594. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  80595. angle -= increment;
  80596. }
  80597. return result;
  80598. };
  80599. Polygon.Parse = function (input) {
  80600. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  80601. var i, result = [];
  80602. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  80603. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  80604. }
  80605. return result;
  80606. };
  80607. Polygon.StartingAt = function (x, y) {
  80608. return BABYLON.Path2.StartingAt(x, y);
  80609. };
  80610. return Polygon;
  80611. }());
  80612. BABYLON.Polygon = Polygon;
  80613. var PolygonMeshBuilder = /** @class */ (function () {
  80614. function PolygonMeshBuilder(name, contours, scene) {
  80615. this._points = new PolygonPoints();
  80616. this._outlinepoints = new PolygonPoints();
  80617. this._holes = new Array();
  80618. this._epoints = new Array();
  80619. this._eholes = new Array();
  80620. this._name = name;
  80621. this._scene = scene;
  80622. var points;
  80623. if (contours instanceof BABYLON.Path2) {
  80624. points = contours.getPoints();
  80625. }
  80626. else {
  80627. points = contours;
  80628. }
  80629. this._addToepoint(points);
  80630. this._points.add(points);
  80631. this._outlinepoints.add(points);
  80632. if (typeof earcut === 'undefined') {
  80633. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  80634. }
  80635. }
  80636. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  80637. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  80638. var p = points_1[_i];
  80639. this._epoints.push(p.x, p.y);
  80640. }
  80641. };
  80642. PolygonMeshBuilder.prototype.addHole = function (hole) {
  80643. this._points.add(hole);
  80644. var holepoints = new PolygonPoints();
  80645. holepoints.add(hole);
  80646. this._holes.push(holepoints);
  80647. this._eholes.push(this._epoints.length / 2);
  80648. this._addToepoint(hole);
  80649. return this;
  80650. };
  80651. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  80652. var _this = this;
  80653. if (updatable === void 0) { updatable = false; }
  80654. if (depth === void 0) { depth = 0; }
  80655. var result = new BABYLON.Mesh(this._name, this._scene);
  80656. var normals = new Array();
  80657. var positions = new Array();
  80658. var uvs = new Array();
  80659. var bounds = this._points.computeBounds();
  80660. this._points.elements.forEach(function (p) {
  80661. normals.push(0, 1.0, 0);
  80662. positions.push(p.x, 0, p.y);
  80663. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  80664. });
  80665. var indices = new Array();
  80666. var res = earcut(this._epoints, this._eholes, 2);
  80667. for (var i = 0; i < res.length; i++) {
  80668. indices.push(res[i]);
  80669. }
  80670. if (depth > 0) {
  80671. var positionscount = (positions.length / 3); //get the current pointcount
  80672. this._points.elements.forEach(function (p) {
  80673. normals.push(0, -1.0, 0);
  80674. positions.push(p.x, -depth, p.y);
  80675. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  80676. });
  80677. var totalCount = indices.length;
  80678. for (var i = 0; i < totalCount; i += 3) {
  80679. var i0 = indices[i + 0];
  80680. var i1 = indices[i + 1];
  80681. var i2 = indices[i + 2];
  80682. indices.push(i2 + positionscount);
  80683. indices.push(i1 + positionscount);
  80684. indices.push(i0 + positionscount);
  80685. }
  80686. //Add the sides
  80687. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  80688. this._holes.forEach(function (hole) {
  80689. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  80690. });
  80691. }
  80692. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  80693. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  80694. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  80695. result.setIndices(indices);
  80696. return result;
  80697. };
  80698. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  80699. var StartIndex = positions.length / 3;
  80700. var ulength = 0;
  80701. for (var i = 0; i < points.elements.length; i++) {
  80702. var p = points.elements[i];
  80703. var p1;
  80704. if ((i + 1) > points.elements.length - 1) {
  80705. p1 = points.elements[0];
  80706. }
  80707. else {
  80708. p1 = points.elements[i + 1];
  80709. }
  80710. positions.push(p.x, 0, p.y);
  80711. positions.push(p.x, -depth, p.y);
  80712. positions.push(p1.x, 0, p1.y);
  80713. positions.push(p1.x, -depth, p1.y);
  80714. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  80715. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  80716. var v3 = v2.subtract(v1);
  80717. var v4 = new BABYLON.Vector3(0, 1, 0);
  80718. var vn = BABYLON.Vector3.Cross(v3, v4);
  80719. vn = vn.normalize();
  80720. uvs.push(ulength / bounds.width, 0);
  80721. uvs.push(ulength / bounds.width, 1);
  80722. ulength += v3.length();
  80723. uvs.push((ulength / bounds.width), 0);
  80724. uvs.push((ulength / bounds.width), 1);
  80725. if (!flip) {
  80726. normals.push(-vn.x, -vn.y, -vn.z);
  80727. normals.push(-vn.x, -vn.y, -vn.z);
  80728. normals.push(-vn.x, -vn.y, -vn.z);
  80729. normals.push(-vn.x, -vn.y, -vn.z);
  80730. indices.push(StartIndex);
  80731. indices.push(StartIndex + 1);
  80732. indices.push(StartIndex + 2);
  80733. indices.push(StartIndex + 1);
  80734. indices.push(StartIndex + 3);
  80735. indices.push(StartIndex + 2);
  80736. }
  80737. else {
  80738. normals.push(vn.x, vn.y, vn.z);
  80739. normals.push(vn.x, vn.y, vn.z);
  80740. normals.push(vn.x, vn.y, vn.z);
  80741. normals.push(vn.x, vn.y, vn.z);
  80742. indices.push(StartIndex);
  80743. indices.push(StartIndex + 2);
  80744. indices.push(StartIndex + 1);
  80745. indices.push(StartIndex + 1);
  80746. indices.push(StartIndex + 2);
  80747. indices.push(StartIndex + 3);
  80748. }
  80749. StartIndex += 4;
  80750. }
  80751. ;
  80752. };
  80753. return PolygonMeshBuilder;
  80754. }());
  80755. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  80756. })(BABYLON || (BABYLON = {}));
  80757. //# sourceMappingURL=babylon.polygonMesh.js.map
  80758. var BABYLON;
  80759. (function (BABYLON) {
  80760. // Unique ID when we import meshes from Babylon to CSG
  80761. var currentCSGMeshId = 0;
  80762. // # class Vertex
  80763. // Represents a vertex of a polygon. Use your own vertex class instead of this
  80764. // one to provide additional features like texture coordinates and vertex
  80765. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  80766. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  80767. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  80768. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  80769. // is not used anywhere else.
  80770. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  80771. var Vertex = /** @class */ (function () {
  80772. function Vertex(pos, normal, uv) {
  80773. this.pos = pos;
  80774. this.normal = normal;
  80775. this.uv = uv;
  80776. }
  80777. Vertex.prototype.clone = function () {
  80778. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  80779. };
  80780. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  80781. // orientation of a polygon is flipped.
  80782. Vertex.prototype.flip = function () {
  80783. this.normal = this.normal.scale(-1);
  80784. };
  80785. // Create a new vertex between this vertex and `other` by linearly
  80786. // interpolating all properties using a parameter of `t`. Subclasses should
  80787. // override this to interpolate additional properties.
  80788. Vertex.prototype.interpolate = function (other, t) {
  80789. 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));
  80790. };
  80791. return Vertex;
  80792. }());
  80793. // # class Plane
  80794. // Represents a plane in 3D space.
  80795. var Plane = /** @class */ (function () {
  80796. function Plane(normal, w) {
  80797. this.normal = normal;
  80798. this.w = w;
  80799. }
  80800. Plane.FromPoints = function (a, b, c) {
  80801. var v0 = c.subtract(a);
  80802. var v1 = b.subtract(a);
  80803. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  80804. return null;
  80805. }
  80806. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  80807. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  80808. };
  80809. Plane.prototype.clone = function () {
  80810. return new Plane(this.normal.clone(), this.w);
  80811. };
  80812. Plane.prototype.flip = function () {
  80813. this.normal.scaleInPlace(-1);
  80814. this.w = -this.w;
  80815. };
  80816. // Split `polygon` by this plane if needed, then put the polygon or polygon
  80817. // fragments in the appropriate lists. Coplanar polygons go into either
  80818. // `coplanarFront` or `coplanarBack` depending on their orientation with
  80819. // respect to this plane. Polygons in front or in back of this plane go into
  80820. // either `front` or `back`.
  80821. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  80822. var COPLANAR = 0;
  80823. var FRONT = 1;
  80824. var BACK = 2;
  80825. var SPANNING = 3;
  80826. // Classify each point as well as the entire polygon into one of the above
  80827. // four classes.
  80828. var polygonType = 0;
  80829. var types = [];
  80830. var i;
  80831. var t;
  80832. for (i = 0; i < polygon.vertices.length; i++) {
  80833. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  80834. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  80835. polygonType |= type;
  80836. types.push(type);
  80837. }
  80838. // Put the polygon in the correct list, splitting it when necessary.
  80839. switch (polygonType) {
  80840. case COPLANAR:
  80841. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  80842. break;
  80843. case FRONT:
  80844. front.push(polygon);
  80845. break;
  80846. case BACK:
  80847. back.push(polygon);
  80848. break;
  80849. case SPANNING:
  80850. var f = [], b = [];
  80851. for (i = 0; i < polygon.vertices.length; i++) {
  80852. var j = (i + 1) % polygon.vertices.length;
  80853. var ti = types[i], tj = types[j];
  80854. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  80855. if (ti !== BACK)
  80856. f.push(vi);
  80857. if (ti !== FRONT)
  80858. b.push(ti !== BACK ? vi.clone() : vi);
  80859. if ((ti | tj) === SPANNING) {
  80860. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  80861. var v = vi.interpolate(vj, t);
  80862. f.push(v);
  80863. b.push(v.clone());
  80864. }
  80865. }
  80866. var poly;
  80867. if (f.length >= 3) {
  80868. poly = new Polygon(f, polygon.shared);
  80869. if (poly.plane)
  80870. front.push(poly);
  80871. }
  80872. if (b.length >= 3) {
  80873. poly = new Polygon(b, polygon.shared);
  80874. if (poly.plane)
  80875. back.push(poly);
  80876. }
  80877. break;
  80878. }
  80879. };
  80880. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  80881. // point is on the plane.
  80882. Plane.EPSILON = 1e-5;
  80883. return Plane;
  80884. }());
  80885. // # class Polygon
  80886. // Represents a convex polygon. The vertices used to initialize a polygon must
  80887. // be coplanar and form a convex loop.
  80888. //
  80889. // Each convex polygon has a `shared` property, which is shared between all
  80890. // polygons that are clones of each other or were split from the same polygon.
  80891. // This can be used to define per-polygon properties (such as surface color).
  80892. var Polygon = /** @class */ (function () {
  80893. function Polygon(vertices, shared) {
  80894. this.vertices = vertices;
  80895. this.shared = shared;
  80896. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  80897. }
  80898. Polygon.prototype.clone = function () {
  80899. var vertices = this.vertices.map(function (v) { return v.clone(); });
  80900. return new Polygon(vertices, this.shared);
  80901. };
  80902. Polygon.prototype.flip = function () {
  80903. this.vertices.reverse().map(function (v) { v.flip(); });
  80904. this.plane.flip();
  80905. };
  80906. return Polygon;
  80907. }());
  80908. // # class Node
  80909. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  80910. // by picking a polygon to split along. That polygon (and all other coplanar
  80911. // polygons) are added directly to that node and the other polygons are added to
  80912. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  80913. // no distinction between internal and leaf nodes.
  80914. var Node = /** @class */ (function () {
  80915. function Node(polygons) {
  80916. this.plane = null;
  80917. this.front = null;
  80918. this.back = null;
  80919. this.polygons = new Array();
  80920. if (polygons) {
  80921. this.build(polygons);
  80922. }
  80923. }
  80924. Node.prototype.clone = function () {
  80925. var node = new Node();
  80926. node.plane = this.plane && this.plane.clone();
  80927. node.front = this.front && this.front.clone();
  80928. node.back = this.back && this.back.clone();
  80929. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  80930. return node;
  80931. };
  80932. // Convert solid space to empty space and empty space to solid space.
  80933. Node.prototype.invert = function () {
  80934. for (var i = 0; i < this.polygons.length; i++) {
  80935. this.polygons[i].flip();
  80936. }
  80937. if (this.plane) {
  80938. this.plane.flip();
  80939. }
  80940. if (this.front) {
  80941. this.front.invert();
  80942. }
  80943. if (this.back) {
  80944. this.back.invert();
  80945. }
  80946. var temp = this.front;
  80947. this.front = this.back;
  80948. this.back = temp;
  80949. };
  80950. // Recursively remove all polygons in `polygons` that are inside this BSP
  80951. // tree.
  80952. Node.prototype.clipPolygons = function (polygons) {
  80953. if (!this.plane)
  80954. return polygons.slice();
  80955. var front = new Array(), back = new Array();
  80956. for (var i = 0; i < polygons.length; i++) {
  80957. this.plane.splitPolygon(polygons[i], front, back, front, back);
  80958. }
  80959. if (this.front) {
  80960. front = this.front.clipPolygons(front);
  80961. }
  80962. if (this.back) {
  80963. back = this.back.clipPolygons(back);
  80964. }
  80965. else {
  80966. back = [];
  80967. }
  80968. return front.concat(back);
  80969. };
  80970. // Remove all polygons in this BSP tree that are inside the other BSP tree
  80971. // `bsp`.
  80972. Node.prototype.clipTo = function (bsp) {
  80973. this.polygons = bsp.clipPolygons(this.polygons);
  80974. if (this.front)
  80975. this.front.clipTo(bsp);
  80976. if (this.back)
  80977. this.back.clipTo(bsp);
  80978. };
  80979. // Return a list of all polygons in this BSP tree.
  80980. Node.prototype.allPolygons = function () {
  80981. var polygons = this.polygons.slice();
  80982. if (this.front)
  80983. polygons = polygons.concat(this.front.allPolygons());
  80984. if (this.back)
  80985. polygons = polygons.concat(this.back.allPolygons());
  80986. return polygons;
  80987. };
  80988. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  80989. // new polygons are filtered down to the bottom of the tree and become new
  80990. // nodes there. Each set of polygons is partitioned using the first polygon
  80991. // (no heuristic is used to pick a good split).
  80992. Node.prototype.build = function (polygons) {
  80993. if (!polygons.length)
  80994. return;
  80995. if (!this.plane)
  80996. this.plane = polygons[0].plane.clone();
  80997. var front = new Array(), back = new Array();
  80998. for (var i = 0; i < polygons.length; i++) {
  80999. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  81000. }
  81001. if (front.length) {
  81002. if (!this.front)
  81003. this.front = new Node();
  81004. this.front.build(front);
  81005. }
  81006. if (back.length) {
  81007. if (!this.back)
  81008. this.back = new Node();
  81009. this.back.build(back);
  81010. }
  81011. };
  81012. return Node;
  81013. }());
  81014. var CSG = /** @class */ (function () {
  81015. function CSG() {
  81016. this.polygons = new Array();
  81017. }
  81018. // Convert BABYLON.Mesh to BABYLON.CSG
  81019. CSG.FromMesh = function (mesh) {
  81020. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  81021. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  81022. if (mesh instanceof BABYLON.Mesh) {
  81023. mesh.computeWorldMatrix(true);
  81024. matrix = mesh.getWorldMatrix();
  81025. meshPosition = mesh.position.clone();
  81026. meshRotation = mesh.rotation.clone();
  81027. if (mesh.rotationQuaternion) {
  81028. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  81029. }
  81030. meshScaling = mesh.scaling.clone();
  81031. }
  81032. else {
  81033. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  81034. }
  81035. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  81036. var subMeshes = mesh.subMeshes;
  81037. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  81038. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  81039. vertices = [];
  81040. for (var j = 0; j < 3; j++) {
  81041. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  81042. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  81043. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  81044. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  81045. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  81046. vertex = new Vertex(position, normal, uv);
  81047. vertices.push(vertex);
  81048. }
  81049. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  81050. // To handle the case of degenerated triangle
  81051. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  81052. if (polygon.plane)
  81053. polygons.push(polygon);
  81054. }
  81055. }
  81056. var csg = CSG.FromPolygons(polygons);
  81057. csg.matrix = matrix;
  81058. csg.position = meshPosition;
  81059. csg.rotation = meshRotation;
  81060. csg.scaling = meshScaling;
  81061. csg.rotationQuaternion = meshRotationQuaternion;
  81062. currentCSGMeshId++;
  81063. return csg;
  81064. };
  81065. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  81066. CSG.FromPolygons = function (polygons) {
  81067. var csg = new CSG();
  81068. csg.polygons = polygons;
  81069. return csg;
  81070. };
  81071. CSG.prototype.clone = function () {
  81072. var csg = new CSG();
  81073. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  81074. csg.copyTransformAttributes(this);
  81075. return csg;
  81076. };
  81077. CSG.prototype.union = function (csg) {
  81078. var a = new Node(this.clone().polygons);
  81079. var b = new Node(csg.clone().polygons);
  81080. a.clipTo(b);
  81081. b.clipTo(a);
  81082. b.invert();
  81083. b.clipTo(a);
  81084. b.invert();
  81085. a.build(b.allPolygons());
  81086. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  81087. };
  81088. CSG.prototype.unionInPlace = function (csg) {
  81089. var a = new Node(this.polygons);
  81090. var b = new Node(csg.polygons);
  81091. a.clipTo(b);
  81092. b.clipTo(a);
  81093. b.invert();
  81094. b.clipTo(a);
  81095. b.invert();
  81096. a.build(b.allPolygons());
  81097. this.polygons = a.allPolygons();
  81098. };
  81099. CSG.prototype.subtract = function (csg) {
  81100. var a = new Node(this.clone().polygons);
  81101. var b = new Node(csg.clone().polygons);
  81102. a.invert();
  81103. a.clipTo(b);
  81104. b.clipTo(a);
  81105. b.invert();
  81106. b.clipTo(a);
  81107. b.invert();
  81108. a.build(b.allPolygons());
  81109. a.invert();
  81110. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  81111. };
  81112. CSG.prototype.subtractInPlace = function (csg) {
  81113. var a = new Node(this.polygons);
  81114. var b = new Node(csg.polygons);
  81115. a.invert();
  81116. a.clipTo(b);
  81117. b.clipTo(a);
  81118. b.invert();
  81119. b.clipTo(a);
  81120. b.invert();
  81121. a.build(b.allPolygons());
  81122. a.invert();
  81123. this.polygons = a.allPolygons();
  81124. };
  81125. CSG.prototype.intersect = function (csg) {
  81126. var a = new Node(this.clone().polygons);
  81127. var b = new Node(csg.clone().polygons);
  81128. a.invert();
  81129. b.clipTo(a);
  81130. b.invert();
  81131. a.clipTo(b);
  81132. b.clipTo(a);
  81133. a.build(b.allPolygons());
  81134. a.invert();
  81135. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  81136. };
  81137. CSG.prototype.intersectInPlace = function (csg) {
  81138. var a = new Node(this.polygons);
  81139. var b = new Node(csg.polygons);
  81140. a.invert();
  81141. b.clipTo(a);
  81142. b.invert();
  81143. a.clipTo(b);
  81144. b.clipTo(a);
  81145. a.build(b.allPolygons());
  81146. a.invert();
  81147. this.polygons = a.allPolygons();
  81148. };
  81149. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  81150. // not modified.
  81151. CSG.prototype.inverse = function () {
  81152. var csg = this.clone();
  81153. csg.inverseInPlace();
  81154. return csg;
  81155. };
  81156. CSG.prototype.inverseInPlace = function () {
  81157. this.polygons.map(function (p) { p.flip(); });
  81158. };
  81159. // This is used to keep meshes transformations so they can be restored
  81160. // when we build back a Babylon Mesh
  81161. // NB : All CSG operations are performed in world coordinates
  81162. CSG.prototype.copyTransformAttributes = function (csg) {
  81163. this.matrix = csg.matrix;
  81164. this.position = csg.position;
  81165. this.rotation = csg.rotation;
  81166. this.scaling = csg.scaling;
  81167. this.rotationQuaternion = csg.rotationQuaternion;
  81168. return this;
  81169. };
  81170. // Build Raw mesh from CSG
  81171. // Coordinates here are in world space
  81172. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  81173. var matrix = this.matrix.clone();
  81174. matrix.invert();
  81175. 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;
  81176. if (keepSubMeshes) {
  81177. // Sort Polygons, since subMeshes are indices range
  81178. polygons.sort(function (a, b) {
  81179. if (a.shared.meshId === b.shared.meshId) {
  81180. return a.shared.subMeshId - b.shared.subMeshId;
  81181. }
  81182. else {
  81183. return a.shared.meshId - b.shared.meshId;
  81184. }
  81185. });
  81186. }
  81187. for (var i = 0, il = polygons.length; i < il; i++) {
  81188. polygon = polygons[i];
  81189. // Building SubMeshes
  81190. if (!subMesh_dict[polygon.shared.meshId]) {
  81191. subMesh_dict[polygon.shared.meshId] = {};
  81192. }
  81193. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  81194. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  81195. indexStart: +Infinity,
  81196. indexEnd: -Infinity,
  81197. materialIndex: polygon.shared.materialIndex
  81198. };
  81199. }
  81200. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  81201. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  81202. polygonIndices[0] = 0;
  81203. polygonIndices[1] = j - 1;
  81204. polygonIndices[2] = j;
  81205. for (var k = 0; k < 3; k++) {
  81206. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  81207. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  81208. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  81209. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  81210. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  81211. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  81212. // Check if 2 points can be merged
  81213. if (!(typeof vertex_idx !== 'undefined' &&
  81214. normals[vertex_idx * 3] === localNormal.x &&
  81215. normals[vertex_idx * 3 + 1] === localNormal.y &&
  81216. normals[vertex_idx * 3 + 2] === localNormal.z &&
  81217. uvs[vertex_idx * 2] === uv.x &&
  81218. uvs[vertex_idx * 2 + 1] === uv.y)) {
  81219. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  81220. uvs.push(uv.x, uv.y);
  81221. normals.push(normal.x, normal.y, normal.z);
  81222. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  81223. }
  81224. indices.push(vertex_idx);
  81225. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  81226. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  81227. currentIndex++;
  81228. }
  81229. }
  81230. }
  81231. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  81232. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  81233. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  81234. mesh.setIndices(indices, null);
  81235. if (keepSubMeshes) {
  81236. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  81237. var materialIndexOffset = 0, materialMaxIndex;
  81238. mesh.subMeshes = new Array();
  81239. for (var m in subMesh_dict) {
  81240. materialMaxIndex = -1;
  81241. for (var sm in subMesh_dict[m]) {
  81242. subMesh_obj = subMesh_dict[m][sm];
  81243. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  81244. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  81245. }
  81246. materialIndexOffset += ++materialMaxIndex;
  81247. }
  81248. }
  81249. return mesh;
  81250. };
  81251. // Build Mesh from CSG taking material and transforms into account
  81252. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  81253. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  81254. mesh.material = material;
  81255. mesh.position.copyFrom(this.position);
  81256. mesh.rotation.copyFrom(this.rotation);
  81257. if (this.rotationQuaternion) {
  81258. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  81259. }
  81260. mesh.scaling.copyFrom(this.scaling);
  81261. mesh.computeWorldMatrix(true);
  81262. return mesh;
  81263. };
  81264. return CSG;
  81265. }());
  81266. BABYLON.CSG = CSG;
  81267. })(BABYLON || (BABYLON = {}));
  81268. //# sourceMappingURL=babylon.csg.js.map
  81269. var BABYLON;
  81270. (function (BABYLON) {
  81271. var LensFlare = /** @class */ (function () {
  81272. function LensFlare(size, position, color, imgUrl, system) {
  81273. this.size = size;
  81274. this.position = position;
  81275. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  81276. this.color = color || new BABYLON.Color3(1, 1, 1);
  81277. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  81278. this._system = system;
  81279. system.lensFlares.push(this);
  81280. }
  81281. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  81282. return new LensFlare(size, position, color, imgUrl, system);
  81283. };
  81284. LensFlare.prototype.dispose = function () {
  81285. if (this.texture) {
  81286. this.texture.dispose();
  81287. }
  81288. // Remove from scene
  81289. var index = this._system.lensFlares.indexOf(this);
  81290. this._system.lensFlares.splice(index, 1);
  81291. };
  81292. ;
  81293. return LensFlare;
  81294. }());
  81295. BABYLON.LensFlare = LensFlare;
  81296. })(BABYLON || (BABYLON = {}));
  81297. //# sourceMappingURL=babylon.lensFlare.js.map
  81298. var BABYLON;
  81299. (function (BABYLON) {
  81300. var LensFlareSystem = /** @class */ (function () {
  81301. function LensFlareSystem(name, emitter, scene) {
  81302. this.name = name;
  81303. this.lensFlares = new Array();
  81304. this.borderLimit = 300;
  81305. this.viewportBorder = 0;
  81306. this.layerMask = 0x0FFFFFFF;
  81307. this._vertexBuffers = {};
  81308. this._isEnabled = true;
  81309. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  81310. this._emitter = emitter;
  81311. this.id = name;
  81312. scene.lensFlareSystems.push(this);
  81313. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  81314. var engine = scene.getEngine();
  81315. // VBO
  81316. var vertices = [];
  81317. vertices.push(1, 1);
  81318. vertices.push(-1, 1);
  81319. vertices.push(-1, -1);
  81320. vertices.push(1, -1);
  81321. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  81322. // Indices
  81323. var indices = [];
  81324. indices.push(0);
  81325. indices.push(1);
  81326. indices.push(2);
  81327. indices.push(0);
  81328. indices.push(2);
  81329. indices.push(3);
  81330. this._indexBuffer = engine.createIndexBuffer(indices);
  81331. // Effects
  81332. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  81333. }
  81334. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  81335. get: function () {
  81336. return this._isEnabled;
  81337. },
  81338. set: function (value) {
  81339. this._isEnabled = value;
  81340. },
  81341. enumerable: true,
  81342. configurable: true
  81343. });
  81344. LensFlareSystem.prototype.getScene = function () {
  81345. return this._scene;
  81346. };
  81347. LensFlareSystem.prototype.getEmitter = function () {
  81348. return this._emitter;
  81349. };
  81350. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  81351. this._emitter = newEmitter;
  81352. };
  81353. LensFlareSystem.prototype.getEmitterPosition = function () {
  81354. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  81355. };
  81356. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  81357. var position = this.getEmitterPosition();
  81358. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  81359. this._positionX = position.x;
  81360. this._positionY = position.y;
  81361. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  81362. if (this.viewportBorder > 0) {
  81363. globalViewport.x -= this.viewportBorder;
  81364. globalViewport.y -= this.viewportBorder;
  81365. globalViewport.width += this.viewportBorder * 2;
  81366. globalViewport.height += this.viewportBorder * 2;
  81367. position.x += this.viewportBorder;
  81368. position.y += this.viewportBorder;
  81369. this._positionX += this.viewportBorder;
  81370. this._positionY += this.viewportBorder;
  81371. }
  81372. if (position.z > 0) {
  81373. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  81374. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  81375. return true;
  81376. }
  81377. return true;
  81378. }
  81379. return false;
  81380. };
  81381. LensFlareSystem.prototype._isVisible = function () {
  81382. if (!this._isEnabled || !this._scene.activeCamera) {
  81383. return false;
  81384. }
  81385. var emitterPosition = this.getEmitterPosition();
  81386. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  81387. var distance = direction.length();
  81388. direction.normalize();
  81389. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  81390. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  81391. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  81392. };
  81393. LensFlareSystem.prototype.render = function () {
  81394. if (!this._effect.isReady() || !this._scene.activeCamera)
  81395. return false;
  81396. var engine = this._scene.getEngine();
  81397. var viewport = this._scene.activeCamera.viewport;
  81398. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  81399. // Position
  81400. if (!this.computeEffectivePosition(globalViewport)) {
  81401. return false;
  81402. }
  81403. // Visibility
  81404. if (!this._isVisible()) {
  81405. return false;
  81406. }
  81407. // Intensity
  81408. var awayX;
  81409. var awayY;
  81410. if (this._positionX < this.borderLimit + globalViewport.x) {
  81411. awayX = this.borderLimit + globalViewport.x - this._positionX;
  81412. }
  81413. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  81414. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  81415. }
  81416. else {
  81417. awayX = 0;
  81418. }
  81419. if (this._positionY < this.borderLimit + globalViewport.y) {
  81420. awayY = this.borderLimit + globalViewport.y - this._positionY;
  81421. }
  81422. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  81423. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  81424. }
  81425. else {
  81426. awayY = 0;
  81427. }
  81428. var away = (awayX > awayY) ? awayX : awayY;
  81429. away -= this.viewportBorder;
  81430. if (away > this.borderLimit) {
  81431. away = this.borderLimit;
  81432. }
  81433. var intensity = 1.0 - (away / this.borderLimit);
  81434. if (intensity < 0) {
  81435. return false;
  81436. }
  81437. if (intensity > 1.0) {
  81438. intensity = 1.0;
  81439. }
  81440. if (this.viewportBorder > 0) {
  81441. globalViewport.x += this.viewportBorder;
  81442. globalViewport.y += this.viewportBorder;
  81443. globalViewport.width -= this.viewportBorder * 2;
  81444. globalViewport.height -= this.viewportBorder * 2;
  81445. this._positionX -= this.viewportBorder;
  81446. this._positionY -= this.viewportBorder;
  81447. }
  81448. // Position
  81449. var centerX = globalViewport.x + globalViewport.width / 2;
  81450. var centerY = globalViewport.y + globalViewport.height / 2;
  81451. var distX = centerX - this._positionX;
  81452. var distY = centerY - this._positionY;
  81453. // Effects
  81454. engine.enableEffect(this._effect);
  81455. engine.setState(false);
  81456. engine.setDepthBuffer(false);
  81457. // VBOs
  81458. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  81459. // Flares
  81460. for (var index = 0; index < this.lensFlares.length; index++) {
  81461. var flare = this.lensFlares[index];
  81462. engine.setAlphaMode(flare.alphaMode);
  81463. var x = centerX - (distX * flare.position);
  81464. var y = centerY - (distY * flare.position);
  81465. var cw = flare.size;
  81466. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  81467. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  81468. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  81469. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  81470. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  81471. // Texture
  81472. this._effect.setTexture("textureSampler", flare.texture);
  81473. // Color
  81474. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  81475. // Draw order
  81476. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  81477. }
  81478. engine.setDepthBuffer(true);
  81479. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  81480. return true;
  81481. };
  81482. LensFlareSystem.prototype.dispose = function () {
  81483. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  81484. if (vertexBuffer) {
  81485. vertexBuffer.dispose();
  81486. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  81487. }
  81488. if (this._indexBuffer) {
  81489. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  81490. this._indexBuffer = null;
  81491. }
  81492. while (this.lensFlares.length) {
  81493. this.lensFlares[0].dispose();
  81494. }
  81495. // Remove from scene
  81496. var index = this._scene.lensFlareSystems.indexOf(this);
  81497. this._scene.lensFlareSystems.splice(index, 1);
  81498. };
  81499. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  81500. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  81501. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  81502. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  81503. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  81504. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  81505. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  81506. var parsedFlare = parsedLensFlareSystem.flares[index];
  81507. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  81508. }
  81509. return lensFlareSystem;
  81510. };
  81511. LensFlareSystem.prototype.serialize = function () {
  81512. var serializationObject = {};
  81513. serializationObject.id = this.id;
  81514. serializationObject.name = this.name;
  81515. serializationObject.emitterId = this.getEmitter().id;
  81516. serializationObject.borderLimit = this.borderLimit;
  81517. serializationObject.flares = [];
  81518. for (var index = 0; index < this.lensFlares.length; index++) {
  81519. var flare = this.lensFlares[index];
  81520. serializationObject.flares.push({
  81521. size: flare.size,
  81522. position: flare.position,
  81523. color: flare.color.asArray(),
  81524. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  81525. });
  81526. }
  81527. return serializationObject;
  81528. };
  81529. return LensFlareSystem;
  81530. }());
  81531. BABYLON.LensFlareSystem = LensFlareSystem;
  81532. })(BABYLON || (BABYLON = {}));
  81533. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  81534. var BABYLON;
  81535. (function (BABYLON) {
  81536. /**
  81537. * This is a holder class for the physics joint created by the physics plugin.
  81538. * It holds a set of functions to control the underlying joint.
  81539. */
  81540. var PhysicsJoint = /** @class */ (function () {
  81541. function PhysicsJoint(type, jointData) {
  81542. this.type = type;
  81543. this.jointData = jointData;
  81544. jointData.nativeParams = jointData.nativeParams || {};
  81545. }
  81546. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  81547. get: function () {
  81548. return this._physicsJoint;
  81549. },
  81550. set: function (newJoint) {
  81551. if (this._physicsJoint) {
  81552. //remove from the wolrd
  81553. }
  81554. this._physicsJoint = newJoint;
  81555. },
  81556. enumerable: true,
  81557. configurable: true
  81558. });
  81559. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  81560. set: function (physicsPlugin) {
  81561. this._physicsPlugin = physicsPlugin;
  81562. },
  81563. enumerable: true,
  81564. configurable: true
  81565. });
  81566. /**
  81567. * Execute a function that is physics-plugin specific.
  81568. * @param {Function} func the function that will be executed.
  81569. * It accepts two parameters: the physics world and the physics joint.
  81570. */
  81571. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  81572. func(this._physicsPlugin.world, this._physicsJoint);
  81573. };
  81574. //TODO check if the native joints are the same
  81575. //Joint Types
  81576. PhysicsJoint.DistanceJoint = 0;
  81577. PhysicsJoint.HingeJoint = 1;
  81578. PhysicsJoint.BallAndSocketJoint = 2;
  81579. PhysicsJoint.WheelJoint = 3;
  81580. PhysicsJoint.SliderJoint = 4;
  81581. //OIMO
  81582. PhysicsJoint.PrismaticJoint = 5;
  81583. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  81584. PhysicsJoint.UniversalJoint = 6;
  81585. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  81586. //Cannon
  81587. //Similar to a Ball-Joint. Different in params
  81588. PhysicsJoint.PointToPointJoint = 8;
  81589. //Cannon only at the moment
  81590. PhysicsJoint.SpringJoint = 9;
  81591. PhysicsJoint.LockJoint = 10;
  81592. return PhysicsJoint;
  81593. }());
  81594. BABYLON.PhysicsJoint = PhysicsJoint;
  81595. /**
  81596. * A class representing a physics distance joint.
  81597. */
  81598. var DistanceJoint = /** @class */ (function (_super) {
  81599. __extends(DistanceJoint, _super);
  81600. function DistanceJoint(jointData) {
  81601. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  81602. }
  81603. /**
  81604. * Update the predefined distance.
  81605. */
  81606. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  81607. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  81608. };
  81609. return DistanceJoint;
  81610. }(PhysicsJoint));
  81611. BABYLON.DistanceJoint = DistanceJoint;
  81612. var MotorEnabledJoint = /** @class */ (function (_super) {
  81613. __extends(MotorEnabledJoint, _super);
  81614. function MotorEnabledJoint(type, jointData) {
  81615. return _super.call(this, type, jointData) || this;
  81616. }
  81617. /**
  81618. * Set the motor values.
  81619. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81620. * @param {number} force the force to apply
  81621. * @param {number} maxForce max force for this motor.
  81622. */
  81623. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  81624. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  81625. };
  81626. /**
  81627. * Set the motor's limits.
  81628. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81629. */
  81630. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  81631. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  81632. };
  81633. return MotorEnabledJoint;
  81634. }(PhysicsJoint));
  81635. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  81636. /**
  81637. * This class represents a single hinge physics joint
  81638. */
  81639. var HingeJoint = /** @class */ (function (_super) {
  81640. __extends(HingeJoint, _super);
  81641. function HingeJoint(jointData) {
  81642. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  81643. }
  81644. /**
  81645. * Set the motor values.
  81646. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81647. * @param {number} force the force to apply
  81648. * @param {number} maxForce max force for this motor.
  81649. */
  81650. HingeJoint.prototype.setMotor = function (force, maxForce) {
  81651. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  81652. };
  81653. /**
  81654. * Set the motor's limits.
  81655. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81656. */
  81657. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  81658. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  81659. };
  81660. return HingeJoint;
  81661. }(MotorEnabledJoint));
  81662. BABYLON.HingeJoint = HingeJoint;
  81663. /**
  81664. * This class represents a dual hinge physics joint (same as wheel joint)
  81665. */
  81666. var Hinge2Joint = /** @class */ (function (_super) {
  81667. __extends(Hinge2Joint, _super);
  81668. function Hinge2Joint(jointData) {
  81669. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  81670. }
  81671. /**
  81672. * Set the motor values.
  81673. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81674. * @param {number} force the force to apply
  81675. * @param {number} maxForce max force for this motor.
  81676. * @param {motorIndex} the motor's index, 0 or 1.
  81677. */
  81678. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  81679. if (motorIndex === void 0) { motorIndex = 0; }
  81680. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  81681. };
  81682. /**
  81683. * Set the motor limits.
  81684. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81685. * @param {number} upperLimit the upper limit
  81686. * @param {number} lowerLimit lower limit
  81687. * @param {motorIndex} the motor's index, 0 or 1.
  81688. */
  81689. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  81690. if (motorIndex === void 0) { motorIndex = 0; }
  81691. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  81692. };
  81693. return Hinge2Joint;
  81694. }(MotorEnabledJoint));
  81695. BABYLON.Hinge2Joint = Hinge2Joint;
  81696. })(BABYLON || (BABYLON = {}));
  81697. //# sourceMappingURL=babylon.physicsJoint.js.map
  81698. var BABYLON;
  81699. (function (BABYLON) {
  81700. var PhysicsImpostor = /** @class */ (function () {
  81701. function PhysicsImpostor(object, type, _options, _scene) {
  81702. if (_options === void 0) { _options = { mass: 0 }; }
  81703. var _this = this;
  81704. this.object = object;
  81705. this.type = type;
  81706. this._options = _options;
  81707. this._scene = _scene;
  81708. this._bodyUpdateRequired = false;
  81709. this._onBeforePhysicsStepCallbacks = new Array();
  81710. this._onAfterPhysicsStepCallbacks = new Array();
  81711. this._onPhysicsCollideCallbacks = [];
  81712. this._deltaPosition = BABYLON.Vector3.Zero();
  81713. this._isDisposed = false;
  81714. //temp variables for parent rotation calculations
  81715. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  81716. this._tmpQuat = new BABYLON.Quaternion();
  81717. this._tmpQuat2 = new BABYLON.Quaternion();
  81718. /**
  81719. * this function is executed by the physics engine.
  81720. */
  81721. this.beforeStep = function () {
  81722. if (!_this._physicsEngine) {
  81723. return;
  81724. }
  81725. _this.object.translate(_this._deltaPosition, -1);
  81726. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  81727. _this.object.computeWorldMatrix(false);
  81728. if (_this.object.parent && _this.object.rotationQuaternion) {
  81729. _this.getParentsRotation();
  81730. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  81731. }
  81732. else {
  81733. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  81734. }
  81735. if (!_this._options.disableBidirectionalTransformation) {
  81736. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  81737. }
  81738. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  81739. func(_this);
  81740. });
  81741. };
  81742. /**
  81743. * this function is executed by the physics engine.
  81744. */
  81745. this.afterStep = function () {
  81746. if (!_this._physicsEngine) {
  81747. return;
  81748. }
  81749. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  81750. func(_this);
  81751. });
  81752. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  81753. // object has now its world rotation. needs to be converted to local.
  81754. if (_this.object.parent && _this.object.rotationQuaternion) {
  81755. _this.getParentsRotation();
  81756. _this._tmpQuat.conjugateInPlace();
  81757. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  81758. }
  81759. // take the position set and make it the absolute position of this object.
  81760. _this.object.setAbsolutePosition(_this.object.position);
  81761. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  81762. _this.object.translate(_this._deltaPosition, 1);
  81763. };
  81764. /**
  81765. * Legacy collision detection event support
  81766. */
  81767. this.onCollideEvent = null;
  81768. //event and body object due to cannon's event-based architecture.
  81769. this.onCollide = function (e) {
  81770. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  81771. return;
  81772. }
  81773. if (!_this._physicsEngine) {
  81774. return;
  81775. }
  81776. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  81777. if (otherImpostor) {
  81778. // Legacy collision detection event support
  81779. if (_this.onCollideEvent) {
  81780. _this.onCollideEvent(_this, otherImpostor);
  81781. }
  81782. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  81783. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  81784. }).forEach(function (obj) {
  81785. obj.callback(_this, otherImpostor);
  81786. });
  81787. }
  81788. };
  81789. //sanity check!
  81790. if (!this.object) {
  81791. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  81792. return;
  81793. }
  81794. //legacy support for old syntax.
  81795. if (!this._scene && object.getScene) {
  81796. this._scene = object.getScene();
  81797. }
  81798. if (!this._scene) {
  81799. return;
  81800. }
  81801. this._physicsEngine = this._scene.getPhysicsEngine();
  81802. if (!this._physicsEngine) {
  81803. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  81804. }
  81805. else {
  81806. //set the object's quaternion, if not set
  81807. if (!this.object.rotationQuaternion) {
  81808. if (this.object.rotation) {
  81809. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  81810. }
  81811. else {
  81812. this.object.rotationQuaternion = new BABYLON.Quaternion();
  81813. }
  81814. }
  81815. //default options params
  81816. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  81817. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  81818. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  81819. this._joints = [];
  81820. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  81821. if (!this.object.parent || this._options.ignoreParent) {
  81822. this._init();
  81823. }
  81824. else if (this.object.parent.physicsImpostor) {
  81825. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  81826. }
  81827. }
  81828. }
  81829. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  81830. get: function () {
  81831. return this._isDisposed;
  81832. },
  81833. enumerable: true,
  81834. configurable: true
  81835. });
  81836. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  81837. get: function () {
  81838. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  81839. },
  81840. set: function (value) {
  81841. this.setMass(value);
  81842. },
  81843. enumerable: true,
  81844. configurable: true
  81845. });
  81846. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  81847. get: function () {
  81848. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  81849. },
  81850. set: function (value) {
  81851. if (!this._physicsEngine) {
  81852. return;
  81853. }
  81854. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  81855. },
  81856. enumerable: true,
  81857. configurable: true
  81858. });
  81859. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  81860. get: function () {
  81861. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  81862. },
  81863. set: function (value) {
  81864. if (!this._physicsEngine) {
  81865. return;
  81866. }
  81867. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  81868. },
  81869. enumerable: true,
  81870. configurable: true
  81871. });
  81872. /**
  81873. * This function will completly initialize this impostor.
  81874. * It will create a new body - but only if this mesh has no parent.
  81875. * If it has, this impostor will not be used other than to define the impostor
  81876. * of the child mesh.
  81877. */
  81878. PhysicsImpostor.prototype._init = function () {
  81879. if (!this._physicsEngine) {
  81880. return;
  81881. }
  81882. this._physicsEngine.removeImpostor(this);
  81883. this.physicsBody = null;
  81884. this._parent = this._parent || this._getPhysicsParent();
  81885. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  81886. this._physicsEngine.addImpostor(this);
  81887. }
  81888. };
  81889. PhysicsImpostor.prototype._getPhysicsParent = function () {
  81890. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  81891. var parentMesh = this.object.parent;
  81892. return parentMesh.physicsImpostor;
  81893. }
  81894. return null;
  81895. };
  81896. /**
  81897. * Should a new body be generated.
  81898. */
  81899. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  81900. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  81901. };
  81902. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  81903. this.forceUpdate();
  81904. };
  81905. /**
  81906. * Force a regeneration of this or the parent's impostor's body.
  81907. * Use under cautious - This will remove all joints already implemented.
  81908. */
  81909. PhysicsImpostor.prototype.forceUpdate = function () {
  81910. this._init();
  81911. if (this.parent && !this._options.ignoreParent) {
  81912. this.parent.forceUpdate();
  81913. }
  81914. };
  81915. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  81916. /*public get mesh(): AbstractMesh {
  81917. return this._mesh;
  81918. }*/
  81919. /**
  81920. * Gets the body that holds this impostor. Either its own, or its parent.
  81921. */
  81922. get: function () {
  81923. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  81924. },
  81925. /**
  81926. * Set the physics body. Used mainly by the physics engine/plugin
  81927. */
  81928. set: function (physicsBody) {
  81929. if (this._physicsBody && this._physicsEngine) {
  81930. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  81931. }
  81932. this._physicsBody = physicsBody;
  81933. this.resetUpdateFlags();
  81934. },
  81935. enumerable: true,
  81936. configurable: true
  81937. });
  81938. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  81939. get: function () {
  81940. return !this._options.ignoreParent && this._parent ? this._parent : null;
  81941. },
  81942. set: function (value) {
  81943. this._parent = value;
  81944. },
  81945. enumerable: true,
  81946. configurable: true
  81947. });
  81948. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  81949. this._bodyUpdateRequired = false;
  81950. };
  81951. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  81952. if (this.object.getBoundingInfo) {
  81953. var q = this.object.rotationQuaternion;
  81954. //reset rotation
  81955. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  81956. //calculate the world matrix with no rotation
  81957. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  81958. var boundingInfo = this.object.getBoundingInfo();
  81959. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  81960. //bring back the rotation
  81961. this.object.rotationQuaternion = q;
  81962. //calculate the world matrix with the new rotation
  81963. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  81964. return size;
  81965. }
  81966. else {
  81967. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  81968. }
  81969. };
  81970. PhysicsImpostor.prototype.getObjectCenter = function () {
  81971. if (this.object.getBoundingInfo) {
  81972. var boundingInfo = this.object.getBoundingInfo();
  81973. return boundingInfo.boundingBox.centerWorld;
  81974. }
  81975. else {
  81976. return this.object.position;
  81977. }
  81978. };
  81979. /**
  81980. * Get a specific parametes from the options parameter.
  81981. */
  81982. PhysicsImpostor.prototype.getParam = function (paramName) {
  81983. return this._options[paramName];
  81984. };
  81985. /**
  81986. * Sets a specific parameter in the options given to the physics plugin
  81987. */
  81988. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  81989. this._options[paramName] = value;
  81990. this._bodyUpdateRequired = true;
  81991. };
  81992. /**
  81993. * Specifically change the body's mass option. Won't recreate the physics body object
  81994. */
  81995. PhysicsImpostor.prototype.setMass = function (mass) {
  81996. if (this.getParam("mass") !== mass) {
  81997. this.setParam("mass", mass);
  81998. }
  81999. if (this._physicsEngine) {
  82000. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  82001. }
  82002. };
  82003. PhysicsImpostor.prototype.getLinearVelocity = function () {
  82004. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  82005. };
  82006. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  82007. if (this._physicsEngine) {
  82008. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  82009. }
  82010. };
  82011. PhysicsImpostor.prototype.getAngularVelocity = function () {
  82012. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  82013. };
  82014. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  82015. if (this._physicsEngine) {
  82016. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  82017. }
  82018. };
  82019. /**
  82020. * Execute a function with the physics plugin native code.
  82021. * Provide a function the will have two variables - the world object and the physics body object.
  82022. */
  82023. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  82024. if (this._physicsEngine) {
  82025. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  82026. }
  82027. };
  82028. /**
  82029. * Register a function that will be executed before the physics world is stepping forward.
  82030. */
  82031. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  82032. this._onBeforePhysicsStepCallbacks.push(func);
  82033. };
  82034. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  82035. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  82036. if (index > -1) {
  82037. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  82038. }
  82039. else {
  82040. BABYLON.Tools.Warn("Function to remove was not found");
  82041. }
  82042. };
  82043. /**
  82044. * Register a function that will be executed after the physics step
  82045. */
  82046. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  82047. this._onAfterPhysicsStepCallbacks.push(func);
  82048. };
  82049. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  82050. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  82051. if (index > -1) {
  82052. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  82053. }
  82054. else {
  82055. BABYLON.Tools.Warn("Function to remove was not found");
  82056. }
  82057. };
  82058. /**
  82059. * register a function that will be executed when this impostor collides against a different body.
  82060. */
  82061. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  82062. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  82063. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  82064. };
  82065. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  82066. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  82067. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  82068. if (index > -1) {
  82069. this._onPhysicsCollideCallbacks.splice(index, 1);
  82070. }
  82071. else {
  82072. BABYLON.Tools.Warn("Function to remove was not found");
  82073. }
  82074. };
  82075. PhysicsImpostor.prototype.getParentsRotation = function () {
  82076. var parent = this.object.parent;
  82077. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  82078. while (parent) {
  82079. if (parent.rotationQuaternion) {
  82080. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  82081. }
  82082. else {
  82083. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  82084. }
  82085. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  82086. parent = parent.parent;
  82087. }
  82088. return this._tmpQuat;
  82089. };
  82090. /**
  82091. * Apply a force
  82092. */
  82093. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  82094. if (this._physicsEngine) {
  82095. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  82096. }
  82097. return this;
  82098. };
  82099. /**
  82100. * Apply an impulse
  82101. */
  82102. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  82103. if (this._physicsEngine) {
  82104. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  82105. }
  82106. return this;
  82107. };
  82108. /**
  82109. * A help function to create a joint.
  82110. */
  82111. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  82112. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  82113. this.addJoint(otherImpostor, joint);
  82114. return this;
  82115. };
  82116. /**
  82117. * Add a joint to this impostor with a different impostor.
  82118. */
  82119. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  82120. this._joints.push({
  82121. otherImpostor: otherImpostor,
  82122. joint: joint
  82123. });
  82124. if (this._physicsEngine) {
  82125. this._physicsEngine.addJoint(this, otherImpostor, joint);
  82126. }
  82127. return this;
  82128. };
  82129. /**
  82130. * Will keep this body still, in a sleep mode.
  82131. */
  82132. PhysicsImpostor.prototype.sleep = function () {
  82133. if (this._physicsEngine) {
  82134. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  82135. }
  82136. return this;
  82137. };
  82138. /**
  82139. * Wake the body up.
  82140. */
  82141. PhysicsImpostor.prototype.wakeUp = function () {
  82142. if (this._physicsEngine) {
  82143. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  82144. }
  82145. return this;
  82146. };
  82147. PhysicsImpostor.prototype.clone = function (newObject) {
  82148. if (!newObject)
  82149. return null;
  82150. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  82151. };
  82152. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  82153. var _this = this;
  82154. //no dispose if no physics engine is available.
  82155. if (!this._physicsEngine) {
  82156. return;
  82157. }
  82158. this._joints.forEach(function (j) {
  82159. if (_this._physicsEngine) {
  82160. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  82161. }
  82162. });
  82163. //dispose the physics body
  82164. this._physicsEngine.removeImpostor(this);
  82165. if (this.parent) {
  82166. this.parent.forceUpdate();
  82167. }
  82168. else {
  82169. /*this._object.getChildMeshes().forEach(function(mesh) {
  82170. if (mesh.physicsImpostor) {
  82171. if (disposeChildren) {
  82172. mesh.physicsImpostor.dispose();
  82173. mesh.physicsImpostor = null;
  82174. }
  82175. }
  82176. })*/
  82177. }
  82178. this._isDisposed = true;
  82179. };
  82180. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  82181. this._deltaPosition.copyFrom(position);
  82182. };
  82183. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  82184. if (!this._deltaRotation) {
  82185. this._deltaRotation = new BABYLON.Quaternion();
  82186. }
  82187. this._deltaRotation.copyFrom(rotation);
  82188. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  82189. };
  82190. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  82191. if (this._physicsEngine) {
  82192. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  82193. }
  82194. return this;
  82195. };
  82196. PhysicsImpostor.prototype.getRadius = function () {
  82197. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  82198. };
  82199. /**
  82200. * Sync a bone with this impostor
  82201. * @param bone The bone to sync to the impostor.
  82202. * @param boneMesh The mesh that the bone is influencing.
  82203. * @param jointPivot The pivot of the joint / bone in local space.
  82204. * @param distToJoint Optional distance from the impostor to the joint.
  82205. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  82206. */
  82207. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  82208. var tempVec = PhysicsImpostor._tmpVecs[0];
  82209. var mesh = this.object;
  82210. if (mesh.rotationQuaternion) {
  82211. if (adjustRotation) {
  82212. var tempQuat = PhysicsImpostor._tmpQuat;
  82213. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  82214. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  82215. }
  82216. else {
  82217. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  82218. }
  82219. }
  82220. tempVec.x = 0;
  82221. tempVec.y = 0;
  82222. tempVec.z = 0;
  82223. if (jointPivot) {
  82224. tempVec.x = jointPivot.x;
  82225. tempVec.y = jointPivot.y;
  82226. tempVec.z = jointPivot.z;
  82227. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  82228. if (distToJoint === undefined || distToJoint === null) {
  82229. distToJoint = jointPivot.length();
  82230. }
  82231. tempVec.x *= distToJoint;
  82232. tempVec.y *= distToJoint;
  82233. tempVec.z *= distToJoint;
  82234. }
  82235. if (bone.getParent()) {
  82236. tempVec.addInPlace(mesh.getAbsolutePosition());
  82237. bone.setAbsolutePosition(tempVec, boneMesh);
  82238. }
  82239. else {
  82240. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  82241. boneMesh.position.x -= tempVec.x;
  82242. boneMesh.position.y -= tempVec.y;
  82243. boneMesh.position.z -= tempVec.z;
  82244. }
  82245. };
  82246. /**
  82247. * Sync impostor to a bone
  82248. * @param bone The bone that the impostor will be synced to.
  82249. * @param boneMesh The mesh that the bone is influencing.
  82250. * @param jointPivot The pivot of the joint / bone in local space.
  82251. * @param distToJoint Optional distance from the impostor to the joint.
  82252. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  82253. * @param boneAxis Optional vector3 axis the bone is aligned with
  82254. */
  82255. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  82256. var mesh = this.object;
  82257. if (mesh.rotationQuaternion) {
  82258. if (adjustRotation) {
  82259. var tempQuat = PhysicsImpostor._tmpQuat;
  82260. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  82261. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  82262. }
  82263. else {
  82264. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  82265. }
  82266. }
  82267. var pos = PhysicsImpostor._tmpVecs[0];
  82268. var boneDir = PhysicsImpostor._tmpVecs[1];
  82269. if (!boneAxis) {
  82270. boneAxis = PhysicsImpostor._tmpVecs[2];
  82271. boneAxis.x = 0;
  82272. boneAxis.y = 1;
  82273. boneAxis.z = 0;
  82274. }
  82275. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  82276. bone.getAbsolutePositionToRef(boneMesh, pos);
  82277. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  82278. distToJoint = jointPivot.length();
  82279. }
  82280. if (distToJoint !== undefined && distToJoint !== null) {
  82281. pos.x += boneDir.x * distToJoint;
  82282. pos.y += boneDir.y * distToJoint;
  82283. pos.z += boneDir.z * distToJoint;
  82284. }
  82285. mesh.setAbsolutePosition(pos);
  82286. };
  82287. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  82288. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  82289. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  82290. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  82291. //Impostor types
  82292. PhysicsImpostor.NoImpostor = 0;
  82293. PhysicsImpostor.SphereImpostor = 1;
  82294. PhysicsImpostor.BoxImpostor = 2;
  82295. PhysicsImpostor.PlaneImpostor = 3;
  82296. PhysicsImpostor.MeshImpostor = 4;
  82297. PhysicsImpostor.CylinderImpostor = 7;
  82298. PhysicsImpostor.ParticleImpostor = 8;
  82299. PhysicsImpostor.HeightmapImpostor = 9;
  82300. return PhysicsImpostor;
  82301. }());
  82302. BABYLON.PhysicsImpostor = PhysicsImpostor;
  82303. })(BABYLON || (BABYLON = {}));
  82304. //# sourceMappingURL=babylon.physicsImpostor.js.map
  82305. var BABYLON;
  82306. (function (BABYLON) {
  82307. var PhysicsEngine = /** @class */ (function () {
  82308. function PhysicsEngine(gravity, _physicsPlugin) {
  82309. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  82310. this._physicsPlugin = _physicsPlugin;
  82311. //new methods and parameters
  82312. this._impostors = [];
  82313. this._joints = [];
  82314. if (!this._physicsPlugin.isSupported()) {
  82315. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  82316. + "Please make sure it is included.");
  82317. }
  82318. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  82319. this.setGravity(gravity);
  82320. this.setTimeStep();
  82321. }
  82322. PhysicsEngine.prototype.setGravity = function (gravity) {
  82323. this.gravity = gravity;
  82324. this._physicsPlugin.setGravity(this.gravity);
  82325. };
  82326. /**
  82327. * Set the time step of the physics engine.
  82328. * default is 1/60.
  82329. * To slow it down, enter 1/600 for example.
  82330. * To speed it up, 1/30
  82331. * @param {number} newTimeStep the new timestep to apply to this world.
  82332. */
  82333. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  82334. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  82335. this._physicsPlugin.setTimeStep(newTimeStep);
  82336. };
  82337. /**
  82338. * Get the time step of the physics engine.
  82339. */
  82340. PhysicsEngine.prototype.getTimeStep = function () {
  82341. return this._physicsPlugin.getTimeStep();
  82342. };
  82343. PhysicsEngine.prototype.dispose = function () {
  82344. this._impostors.forEach(function (impostor) {
  82345. impostor.dispose();
  82346. });
  82347. this._physicsPlugin.dispose();
  82348. };
  82349. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  82350. return this._physicsPlugin.name;
  82351. };
  82352. /**
  82353. * Adding a new impostor for the impostor tracking.
  82354. * This will be done by the impostor itself.
  82355. * @param {PhysicsImpostor} impostor the impostor to add
  82356. */
  82357. PhysicsEngine.prototype.addImpostor = function (impostor) {
  82358. impostor.uniqueId = this._impostors.push(impostor);
  82359. //if no parent, generate the body
  82360. if (!impostor.parent) {
  82361. this._physicsPlugin.generatePhysicsBody(impostor);
  82362. }
  82363. };
  82364. /**
  82365. * Remove an impostor from the engine.
  82366. * This impostor and its mesh will not longer be updated by the physics engine.
  82367. * @param {PhysicsImpostor} impostor the impostor to remove
  82368. */
  82369. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  82370. var index = this._impostors.indexOf(impostor);
  82371. if (index > -1) {
  82372. var removed = this._impostors.splice(index, 1);
  82373. //Is it needed?
  82374. if (removed.length) {
  82375. //this will also remove it from the world.
  82376. removed[0].physicsBody = null;
  82377. }
  82378. }
  82379. };
  82380. /**
  82381. * Add a joint to the physics engine
  82382. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  82383. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  82384. * @param {PhysicsJoint} the joint that will connect both impostors.
  82385. */
  82386. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  82387. var impostorJoint = {
  82388. mainImpostor: mainImpostor,
  82389. connectedImpostor: connectedImpostor,
  82390. joint: joint
  82391. };
  82392. joint.physicsPlugin = this._physicsPlugin;
  82393. this._joints.push(impostorJoint);
  82394. this._physicsPlugin.generateJoint(impostorJoint);
  82395. };
  82396. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  82397. var matchingJoints = this._joints.filter(function (impostorJoint) {
  82398. return (impostorJoint.connectedImpostor === connectedImpostor
  82399. && impostorJoint.joint === joint
  82400. && impostorJoint.mainImpostor === mainImpostor);
  82401. });
  82402. if (matchingJoints.length) {
  82403. this._physicsPlugin.removeJoint(matchingJoints[0]);
  82404. //TODO remove it from the list as well
  82405. }
  82406. };
  82407. /**
  82408. * Called by the scene. no need to call it.
  82409. */
  82410. PhysicsEngine.prototype._step = function (delta) {
  82411. var _this = this;
  82412. //check if any mesh has no body / requires an update
  82413. this._impostors.forEach(function (impostor) {
  82414. if (impostor.isBodyInitRequired()) {
  82415. _this._physicsPlugin.generatePhysicsBody(impostor);
  82416. }
  82417. });
  82418. if (delta > 0.1) {
  82419. delta = 0.1;
  82420. }
  82421. else if (delta <= 0) {
  82422. delta = 1.0 / 60.0;
  82423. }
  82424. this._physicsPlugin.executeStep(delta, this._impostors);
  82425. };
  82426. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  82427. return this._physicsPlugin;
  82428. };
  82429. PhysicsEngine.prototype.getImpostors = function () {
  82430. return this._impostors;
  82431. };
  82432. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  82433. for (var i = 0; i < this._impostors.length; ++i) {
  82434. if (this._impostors[i].object === object) {
  82435. return this._impostors[i];
  82436. }
  82437. }
  82438. return null;
  82439. };
  82440. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  82441. for (var i = 0; i < this._impostors.length; ++i) {
  82442. if (this._impostors[i].physicsBody === body) {
  82443. return this._impostors[i];
  82444. }
  82445. }
  82446. return null;
  82447. };
  82448. // Statics
  82449. PhysicsEngine.Epsilon = 0.001;
  82450. return PhysicsEngine;
  82451. }());
  82452. BABYLON.PhysicsEngine = PhysicsEngine;
  82453. })(BABYLON || (BABYLON = {}));
  82454. //# sourceMappingURL=babylon.physicsEngine.js.map
  82455. var BABYLON;
  82456. (function (BABYLON) {
  82457. var PhysicsHelper = /** @class */ (function () {
  82458. function PhysicsHelper(scene) {
  82459. this._scene = scene;
  82460. this._physicsEngine = this._scene.getPhysicsEngine();
  82461. if (!this._physicsEngine) {
  82462. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  82463. }
  82464. }
  82465. /**
  82466. * @param {Vector3} origin the origin of the explosion
  82467. * @param {number} radius the explosion radius
  82468. * @param {number} strength the explosion strength
  82469. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  82470. */
  82471. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  82472. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82473. if (!this._physicsEngine) {
  82474. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  82475. return null;
  82476. }
  82477. var impostors = this._physicsEngine.getImpostors();
  82478. if (impostors.length === 0) {
  82479. return null;
  82480. }
  82481. var event = new PhysicsRadialExplosionEvent(this._scene);
  82482. impostors.forEach(function (impostor) {
  82483. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  82484. if (!impostorForceAndContactPoint) {
  82485. return;
  82486. }
  82487. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  82488. });
  82489. event.dispose(false);
  82490. return event;
  82491. };
  82492. /**
  82493. * @param {Vector3} origin the origin of the explosion
  82494. * @param {number} radius the explosion radius
  82495. * @param {number} strength the explosion strength
  82496. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  82497. */
  82498. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  82499. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82500. if (!this._physicsEngine) {
  82501. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82502. return null;
  82503. }
  82504. var impostors = this._physicsEngine.getImpostors();
  82505. if (impostors.length === 0) {
  82506. return null;
  82507. }
  82508. var event = new PhysicsRadialExplosionEvent(this._scene);
  82509. impostors.forEach(function (impostor) {
  82510. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  82511. if (!impostorForceAndContactPoint) {
  82512. return;
  82513. }
  82514. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  82515. });
  82516. event.dispose(false);
  82517. return event;
  82518. };
  82519. /**
  82520. * @param {Vector3} origin the origin of the explosion
  82521. * @param {number} radius the explosion radius
  82522. * @param {number} strength the explosion strength
  82523. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  82524. */
  82525. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  82526. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82527. if (!this._physicsEngine) {
  82528. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82529. return null;
  82530. }
  82531. var impostors = this._physicsEngine.getImpostors();
  82532. if (impostors.length === 0) {
  82533. return null;
  82534. }
  82535. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  82536. event.dispose(false);
  82537. return event;
  82538. };
  82539. /**
  82540. * @param {Vector3} origin the origin of the updraft
  82541. * @param {number} radius the radius of the updraft
  82542. * @param {number} strength the strength of the updraft
  82543. * @param {number} height the height of the updraft
  82544. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  82545. */
  82546. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  82547. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  82548. if (!this._physicsEngine) {
  82549. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82550. return null;
  82551. }
  82552. if (this._physicsEngine.getImpostors().length === 0) {
  82553. return null;
  82554. }
  82555. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  82556. event.dispose(false);
  82557. return event;
  82558. };
  82559. /**
  82560. * @param {Vector3} origin the of the vortex
  82561. * @param {number} radius the radius of the vortex
  82562. * @param {number} strength the strength of the vortex
  82563. * @param {number} height the height of the vortex
  82564. */
  82565. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  82566. if (!this._physicsEngine) {
  82567. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82568. return null;
  82569. }
  82570. if (this._physicsEngine.getImpostors().length === 0) {
  82571. return null;
  82572. }
  82573. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  82574. event.dispose(false);
  82575. return event;
  82576. };
  82577. return PhysicsHelper;
  82578. }());
  82579. BABYLON.PhysicsHelper = PhysicsHelper;
  82580. /***** Radial explosion *****/
  82581. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  82582. function PhysicsRadialExplosionEvent(scene) {
  82583. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  82584. this._rays = [];
  82585. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  82586. this._scene = scene;
  82587. }
  82588. /**
  82589. * Returns the data related to the radial explosion event (sphere & rays).
  82590. * @returns {PhysicsRadialExplosionEventData}
  82591. */
  82592. PhysicsRadialExplosionEvent.prototype.getData = function () {
  82593. this._dataFetched = true;
  82594. return {
  82595. sphere: this._sphere,
  82596. rays: this._rays,
  82597. };
  82598. };
  82599. /**
  82600. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  82601. * @param impostor
  82602. * @param {Vector3} origin the origin of the explosion
  82603. * @param {number} radius the explosion radius
  82604. * @param {number} strength the explosion strength
  82605. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  82606. * @returns {Nullable<PhysicsForceAndContactPoint>}
  82607. */
  82608. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  82609. if (impostor.mass === 0) {
  82610. return null;
  82611. }
  82612. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  82613. return null;
  82614. }
  82615. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  82616. return null;
  82617. }
  82618. var impostorObjectCenter = impostor.getObjectCenter();
  82619. var direction = impostorObjectCenter.subtract(origin);
  82620. var ray = new BABYLON.Ray(origin, direction, radius);
  82621. this._rays.push(ray);
  82622. var hit = ray.intersectsMesh(impostor.object);
  82623. var contactPoint = hit.pickedPoint;
  82624. if (!contactPoint) {
  82625. return null;
  82626. }
  82627. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  82628. if (distanceFromOrigin > radius) {
  82629. return null;
  82630. }
  82631. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  82632. ? strength
  82633. : strength * (1 - (distanceFromOrigin / radius));
  82634. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  82635. return { force: force, contactPoint: contactPoint };
  82636. };
  82637. /**
  82638. * Disposes the sphere.
  82639. * @param {bolean} force
  82640. */
  82641. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  82642. var _this = this;
  82643. if (force === void 0) { force = true; }
  82644. if (force) {
  82645. this._sphere.dispose();
  82646. }
  82647. else {
  82648. setTimeout(function () {
  82649. if (!_this._dataFetched) {
  82650. _this._sphere.dispose();
  82651. }
  82652. }, 0);
  82653. }
  82654. };
  82655. /*** Helpers ***/
  82656. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  82657. if (!this._sphere) {
  82658. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  82659. this._sphere.isVisible = false;
  82660. }
  82661. };
  82662. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  82663. var impostorObject = impostor.object;
  82664. this._prepareSphere();
  82665. this._sphere.position = origin;
  82666. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  82667. this._sphere._updateBoundingInfo();
  82668. this._sphere.computeWorldMatrix(true);
  82669. return this._sphere.intersectsMesh(impostorObject, true);
  82670. };
  82671. return PhysicsRadialExplosionEvent;
  82672. }());
  82673. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  82674. /***** Gravitational Field *****/
  82675. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  82676. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  82677. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82678. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  82679. this._physicsHelper = physicsHelper;
  82680. this._scene = scene;
  82681. this._origin = origin;
  82682. this._radius = radius;
  82683. this._strength = strength;
  82684. this._falloff = falloff;
  82685. this._tickCallback = this._tick.bind(this);
  82686. }
  82687. /**
  82688. * Returns the data related to the gravitational field event (sphere).
  82689. * @returns {PhysicsGravitationalFieldEventData}
  82690. */
  82691. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  82692. this._dataFetched = true;
  82693. return {
  82694. sphere: this._sphere,
  82695. };
  82696. };
  82697. /**
  82698. * Enables the gravitational field.
  82699. */
  82700. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  82701. this._tickCallback.call(this);
  82702. this._scene.registerBeforeRender(this._tickCallback);
  82703. };
  82704. /**
  82705. * Disables the gravitational field.
  82706. */
  82707. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  82708. this._scene.unregisterBeforeRender(this._tickCallback);
  82709. };
  82710. /**
  82711. * Disposes the sphere.
  82712. * @param {bolean} force
  82713. */
  82714. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  82715. var _this = this;
  82716. if (force === void 0) { force = true; }
  82717. if (force) {
  82718. this._sphere.dispose();
  82719. }
  82720. else {
  82721. setTimeout(function () {
  82722. if (!_this._dataFetched) {
  82723. _this._sphere.dispose();
  82724. }
  82725. }, 0);
  82726. }
  82727. };
  82728. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  82729. // Since the params won't change, we fetch the event only once
  82730. if (this._sphere) {
  82731. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  82732. }
  82733. else {
  82734. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  82735. if (radialExplosionEvent) {
  82736. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  82737. }
  82738. }
  82739. };
  82740. return PhysicsGravitationalFieldEvent;
  82741. }());
  82742. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  82743. /***** Updraft *****/
  82744. var PhysicsUpdraftEvent = /** @class */ (function () {
  82745. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  82746. this._scene = _scene;
  82747. this._origin = _origin;
  82748. this._radius = _radius;
  82749. this._strength = _strength;
  82750. this._height = _height;
  82751. this._updraftMode = _updraftMode;
  82752. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  82753. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  82754. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  82755. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  82756. this._physicsEngine = this._scene.getPhysicsEngine();
  82757. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  82758. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  82759. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  82760. this._originDirection = this._origin.subtract(this._originTop).normalize();
  82761. }
  82762. this._tickCallback = this._tick.bind(this);
  82763. }
  82764. /**
  82765. * Returns the data related to the updraft event (cylinder).
  82766. * @returns {PhysicsUpdraftEventData}
  82767. */
  82768. PhysicsUpdraftEvent.prototype.getData = function () {
  82769. this._dataFetched = true;
  82770. return {
  82771. cylinder: this._cylinder,
  82772. };
  82773. };
  82774. /**
  82775. * Enables the updraft.
  82776. */
  82777. PhysicsUpdraftEvent.prototype.enable = function () {
  82778. this._tickCallback.call(this);
  82779. this._scene.registerBeforeRender(this._tickCallback);
  82780. };
  82781. /**
  82782. * Disables the cortex.
  82783. */
  82784. PhysicsUpdraftEvent.prototype.disable = function () {
  82785. this._scene.unregisterBeforeRender(this._tickCallback);
  82786. };
  82787. /**
  82788. * Disposes the sphere.
  82789. * @param {bolean} force
  82790. */
  82791. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  82792. var _this = this;
  82793. if (force === void 0) { force = true; }
  82794. if (force) {
  82795. this._cylinder.dispose();
  82796. }
  82797. else {
  82798. setTimeout(function () {
  82799. if (!_this._dataFetched) {
  82800. _this._cylinder.dispose();
  82801. }
  82802. }, 0);
  82803. }
  82804. };
  82805. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  82806. if (impostor.mass === 0) {
  82807. return null;
  82808. }
  82809. if (!this._intersectsWithCylinder(impostor)) {
  82810. return null;
  82811. }
  82812. var impostorObjectCenter = impostor.getObjectCenter();
  82813. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  82814. var direction = this._originDirection;
  82815. }
  82816. else {
  82817. var direction = impostorObjectCenter.subtract(this._originTop);
  82818. }
  82819. var multiplier = this._strength * -1;
  82820. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  82821. return { force: force, contactPoint: impostorObjectCenter };
  82822. };
  82823. PhysicsUpdraftEvent.prototype._tick = function () {
  82824. var _this = this;
  82825. this._physicsEngine.getImpostors().forEach(function (impostor) {
  82826. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  82827. if (!impostorForceAndContactPoint) {
  82828. return;
  82829. }
  82830. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  82831. });
  82832. };
  82833. /*** Helpers ***/
  82834. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  82835. if (!this._cylinder) {
  82836. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  82837. height: this._height,
  82838. diameter: this._radius * 2,
  82839. }, this._scene);
  82840. this._cylinder.isVisible = false;
  82841. }
  82842. };
  82843. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  82844. var impostorObject = impostor.object;
  82845. this._prepareCylinder();
  82846. this._cylinder.position = this._cylinderPosition;
  82847. return this._cylinder.intersectsMesh(impostorObject, true);
  82848. };
  82849. return PhysicsUpdraftEvent;
  82850. }());
  82851. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  82852. /***** Vortex *****/
  82853. var PhysicsVortexEvent = /** @class */ (function () {
  82854. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  82855. this._scene = _scene;
  82856. this._origin = _origin;
  82857. this._radius = _radius;
  82858. this._strength = _strength;
  82859. this._height = _height;
  82860. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  82861. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  82862. this._updraftMultiplier = 0.02;
  82863. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  82864. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  82865. this._physicsEngine = this._scene.getPhysicsEngine();
  82866. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  82867. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  82868. this._tickCallback = this._tick.bind(this);
  82869. }
  82870. /**
  82871. * Returns the data related to the vortex event (cylinder).
  82872. * @returns {PhysicsVortexEventData}
  82873. */
  82874. PhysicsVortexEvent.prototype.getData = function () {
  82875. this._dataFetched = true;
  82876. return {
  82877. cylinder: this._cylinder,
  82878. };
  82879. };
  82880. /**
  82881. * Enables the vortex.
  82882. */
  82883. PhysicsVortexEvent.prototype.enable = function () {
  82884. this._tickCallback.call(this);
  82885. this._scene.registerBeforeRender(this._tickCallback);
  82886. };
  82887. /**
  82888. * Disables the cortex.
  82889. */
  82890. PhysicsVortexEvent.prototype.disable = function () {
  82891. this._scene.unregisterBeforeRender(this._tickCallback);
  82892. };
  82893. /**
  82894. * Disposes the sphere.
  82895. * @param {bolean} force
  82896. */
  82897. PhysicsVortexEvent.prototype.dispose = function (force) {
  82898. var _this = this;
  82899. if (force === void 0) { force = true; }
  82900. if (force) {
  82901. this._cylinder.dispose();
  82902. }
  82903. else {
  82904. setTimeout(function () {
  82905. if (!_this._dataFetched) {
  82906. _this._cylinder.dispose();
  82907. }
  82908. }, 0);
  82909. }
  82910. };
  82911. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  82912. if (impostor.mass === 0) {
  82913. return null;
  82914. }
  82915. if (!this._intersectsWithCylinder(impostor)) {
  82916. return null;
  82917. }
  82918. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  82919. return null;
  82920. }
  82921. var impostorObjectCenter = impostor.getObjectCenter();
  82922. 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)
  82923. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  82924. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  82925. var hit = ray.intersectsMesh(impostor.object);
  82926. var contactPoint = hit.pickedPoint;
  82927. if (!contactPoint) {
  82928. return null;
  82929. }
  82930. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  82931. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  82932. var directionToOrigin = contactPoint.normalize();
  82933. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  82934. directionToOrigin = directionToOrigin.negate();
  82935. }
  82936. // TODO: find a more physically based solution
  82937. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  82938. var forceX = directionToOrigin.x * this._strength / 8;
  82939. var forceY = directionToOrigin.y * this._updraftMultiplier;
  82940. var forceZ = directionToOrigin.z * this._strength / 8;
  82941. }
  82942. else {
  82943. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  82944. var forceY = this._originTop.y * this._updraftMultiplier;
  82945. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  82946. }
  82947. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  82948. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  82949. return { force: force, contactPoint: impostorObjectCenter };
  82950. };
  82951. PhysicsVortexEvent.prototype._tick = function () {
  82952. var _this = this;
  82953. this._physicsEngine.getImpostors().forEach(function (impostor) {
  82954. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  82955. if (!impostorForceAndContactPoint) {
  82956. return;
  82957. }
  82958. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  82959. });
  82960. };
  82961. /*** Helpers ***/
  82962. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  82963. if (!this._cylinder) {
  82964. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  82965. height: this._height,
  82966. diameter: this._radius * 2,
  82967. }, this._scene);
  82968. this._cylinder.isVisible = false;
  82969. }
  82970. };
  82971. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  82972. var impostorObject = impostor.object;
  82973. this._prepareCylinder();
  82974. this._cylinder.position = this._cylinderPosition;
  82975. return this._cylinder.intersectsMesh(impostorObject, true);
  82976. };
  82977. return PhysicsVortexEvent;
  82978. }());
  82979. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  82980. /***** Enums *****/
  82981. /**
  82982. * The strenght of the force in correspondence to the distance of the affected object
  82983. */
  82984. var PhysicsRadialImpulseFalloff;
  82985. (function (PhysicsRadialImpulseFalloff) {
  82986. /** Defines that impulse is constant in strength across it's whole radius */
  82987. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  82988. /** DEfines that impulse gets weaker if it's further from the origin */
  82989. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  82990. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  82991. /**
  82992. * The strenght of the force in correspondence to the distance of the affected object
  82993. */
  82994. var PhysicsUpdraftMode;
  82995. (function (PhysicsUpdraftMode) {
  82996. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  82997. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  82998. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  82999. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  83000. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  83001. })(BABYLON || (BABYLON = {}));
  83002. //# sourceMappingURL=babylon.physicsHelper.js.map
  83003. var BABYLON;
  83004. (function (BABYLON) {
  83005. var CannonJSPlugin = /** @class */ (function () {
  83006. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  83007. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  83008. if (iterations === void 0) { iterations = 10; }
  83009. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  83010. this.name = "CannonJSPlugin";
  83011. this._physicsMaterials = new Array();
  83012. this._fixedTimeStep = 1 / 60;
  83013. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  83014. this.BJSCANNON = CANNON;
  83015. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  83016. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  83017. this._tmpPosition = BABYLON.Vector3.Zero();
  83018. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  83019. this._tmpUnityRotation = new BABYLON.Quaternion();
  83020. if (!this.isSupported()) {
  83021. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  83022. return;
  83023. }
  83024. this._extendNamespace();
  83025. this.world = new this.BJSCANNON.World();
  83026. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  83027. this.world.solver.iterations = iterations;
  83028. }
  83029. CannonJSPlugin.prototype.setGravity = function (gravity) {
  83030. this.world.gravity.copy(gravity);
  83031. };
  83032. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  83033. this._fixedTimeStep = timeStep;
  83034. };
  83035. CannonJSPlugin.prototype.getTimeStep = function () {
  83036. return this._fixedTimeStep;
  83037. };
  83038. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  83039. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  83040. };
  83041. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  83042. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  83043. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  83044. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  83045. };
  83046. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  83047. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  83048. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  83049. impostor.physicsBody.applyForce(impulse, worldPoint);
  83050. };
  83051. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  83052. //parent-child relationship. Does this impostor has a parent impostor?
  83053. if (impostor.parent) {
  83054. if (impostor.physicsBody) {
  83055. this.removePhysicsBody(impostor);
  83056. //TODO is that needed?
  83057. impostor.forceUpdate();
  83058. }
  83059. return;
  83060. }
  83061. //should a new body be created for this impostor?
  83062. if (impostor.isBodyInitRequired()) {
  83063. var shape = this._createShape(impostor);
  83064. //unregister events, if body is being changed
  83065. var oldBody = impostor.physicsBody;
  83066. if (oldBody) {
  83067. this.removePhysicsBody(impostor);
  83068. }
  83069. //create the body and material
  83070. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  83071. var bodyCreationObject = {
  83072. mass: impostor.getParam("mass"),
  83073. material: material
  83074. };
  83075. // A simple extend, in case native options were used.
  83076. var nativeOptions = impostor.getParam("nativeOptions");
  83077. for (var key in nativeOptions) {
  83078. if (nativeOptions.hasOwnProperty(key)) {
  83079. bodyCreationObject[key] = nativeOptions[key];
  83080. }
  83081. }
  83082. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  83083. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  83084. this.world.addEventListener("preStep", impostor.beforeStep);
  83085. this.world.addEventListener("postStep", impostor.afterStep);
  83086. impostor.physicsBody.addShape(shape);
  83087. this.world.add(impostor.physicsBody);
  83088. //try to keep the body moving in the right direction by taking old properties.
  83089. //Should be tested!
  83090. if (oldBody) {
  83091. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  83092. impostor.physicsBody[param].copy(oldBody[param]);
  83093. });
  83094. }
  83095. this._processChildMeshes(impostor);
  83096. }
  83097. //now update the body's transformation
  83098. this._updatePhysicsBodyTransformation(impostor);
  83099. };
  83100. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  83101. var _this = this;
  83102. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  83103. var currentRotation = mainImpostor.object.rotationQuaternion;
  83104. if (meshChildren.length) {
  83105. var processMesh = function (localPosition, mesh) {
  83106. if (!currentRotation || !mesh.rotationQuaternion) {
  83107. return;
  83108. }
  83109. var childImpostor = mesh.getPhysicsImpostor();
  83110. if (childImpostor) {
  83111. var parent = childImpostor.parent;
  83112. if (parent !== mainImpostor) {
  83113. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  83114. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  83115. if (childImpostor.physicsBody) {
  83116. _this.removePhysicsBody(childImpostor);
  83117. childImpostor.physicsBody = null;
  83118. }
  83119. childImpostor.parent = mainImpostor;
  83120. childImpostor.resetUpdateFlags();
  83121. 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));
  83122. //Add the mass of the children.
  83123. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  83124. }
  83125. }
  83126. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  83127. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  83128. };
  83129. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  83130. }
  83131. };
  83132. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  83133. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  83134. this.world.removeEventListener("preStep", impostor.beforeStep);
  83135. this.world.removeEventListener("postStep", impostor.afterStep);
  83136. this.world.remove(impostor.physicsBody);
  83137. };
  83138. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  83139. var mainBody = impostorJoint.mainImpostor.physicsBody;
  83140. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  83141. if (!mainBody || !connectedBody) {
  83142. return;
  83143. }
  83144. var constraint;
  83145. var jointData = impostorJoint.joint.jointData;
  83146. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  83147. var constraintData = {
  83148. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  83149. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  83150. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  83151. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  83152. maxForce: jointData.nativeParams.maxForce,
  83153. collideConnected: !!jointData.collision
  83154. };
  83155. switch (impostorJoint.joint.type) {
  83156. case BABYLON.PhysicsJoint.HingeJoint:
  83157. case BABYLON.PhysicsJoint.Hinge2Joint:
  83158. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  83159. break;
  83160. case BABYLON.PhysicsJoint.DistanceJoint:
  83161. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  83162. break;
  83163. case BABYLON.PhysicsJoint.SpringJoint:
  83164. var springData = jointData;
  83165. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  83166. restLength: springData.length,
  83167. stiffness: springData.stiffness,
  83168. damping: springData.damping,
  83169. localAnchorA: constraintData.pivotA,
  83170. localAnchorB: constraintData.pivotB
  83171. });
  83172. break;
  83173. case BABYLON.PhysicsJoint.LockJoint:
  83174. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  83175. break;
  83176. case BABYLON.PhysicsJoint.PointToPointJoint:
  83177. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  83178. default:
  83179. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  83180. break;
  83181. }
  83182. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  83183. constraint.collideConnected = !!jointData.collision;
  83184. impostorJoint.joint.physicsJoint = constraint;
  83185. //don't add spring as constraint, as it is not one.
  83186. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  83187. this.world.addConstraint(constraint);
  83188. }
  83189. else {
  83190. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  83191. constraint.applyForce();
  83192. });
  83193. }
  83194. };
  83195. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  83196. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  83197. };
  83198. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  83199. var index;
  83200. var mat;
  83201. for (index = 0; index < this._physicsMaterials.length; index++) {
  83202. mat = this._physicsMaterials[index];
  83203. if (mat.friction === friction && mat.restitution === restitution) {
  83204. return mat;
  83205. }
  83206. }
  83207. var currentMat = new this.BJSCANNON.Material(name);
  83208. currentMat.friction = friction;
  83209. currentMat.restitution = restitution;
  83210. this._physicsMaterials.push(currentMat);
  83211. return currentMat;
  83212. };
  83213. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  83214. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  83215. };
  83216. CannonJSPlugin.prototype._createShape = function (impostor) {
  83217. var object = impostor.object;
  83218. var returnValue;
  83219. var extendSize = impostor.getObjectExtendSize();
  83220. switch (impostor.type) {
  83221. case BABYLON.PhysicsImpostor.SphereImpostor:
  83222. var radiusX = extendSize.x;
  83223. var radiusY = extendSize.y;
  83224. var radiusZ = extendSize.z;
  83225. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  83226. break;
  83227. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  83228. case BABYLON.PhysicsImpostor.CylinderImpostor:
  83229. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  83230. break;
  83231. case BABYLON.PhysicsImpostor.BoxImpostor:
  83232. var box = extendSize.scale(0.5);
  83233. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  83234. break;
  83235. case BABYLON.PhysicsImpostor.PlaneImpostor:
  83236. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  83237. returnValue = new this.BJSCANNON.Plane();
  83238. break;
  83239. case BABYLON.PhysicsImpostor.MeshImpostor:
  83240. // should transform the vertex data to world coordinates!!
  83241. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  83242. var rawFaces = object.getIndices ? object.getIndices() : [];
  83243. if (!rawVerts)
  83244. return;
  83245. // get only scale! so the object could transform correctly.
  83246. var oldPosition = object.position.clone();
  83247. var oldRotation = object.rotation && object.rotation.clone();
  83248. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  83249. object.position.copyFromFloats(0, 0, 0);
  83250. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  83251. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  83252. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  83253. var transform = object.computeWorldMatrix(true);
  83254. // convert rawVerts to object space
  83255. var temp = new Array();
  83256. var index;
  83257. for (index = 0; index < rawVerts.length; index += 3) {
  83258. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  83259. }
  83260. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  83261. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  83262. //now set back the transformation!
  83263. object.position.copyFrom(oldPosition);
  83264. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  83265. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  83266. break;
  83267. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  83268. var oldPosition2 = object.position.clone();
  83269. var oldRotation2 = object.rotation && object.rotation.clone();
  83270. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  83271. object.position.copyFromFloats(0, 0, 0);
  83272. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  83273. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  83274. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  83275. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  83276. returnValue = this._createHeightmap(object);
  83277. object.position.copyFrom(oldPosition2);
  83278. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  83279. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  83280. object.computeWorldMatrix(true);
  83281. break;
  83282. case BABYLON.PhysicsImpostor.ParticleImpostor:
  83283. returnValue = new this.BJSCANNON.Particle();
  83284. break;
  83285. }
  83286. return returnValue;
  83287. };
  83288. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  83289. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  83290. var transform = object.computeWorldMatrix(true);
  83291. // convert rawVerts to object space
  83292. var temp = new Array();
  83293. var index;
  83294. for (index = 0; index < pos.length; index += 3) {
  83295. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  83296. }
  83297. pos = temp;
  83298. var matrix = new Array();
  83299. //For now pointDepth will not be used and will be automatically calculated.
  83300. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  83301. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  83302. var boundingInfo = object.getBoundingInfo();
  83303. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  83304. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  83305. var elementSize = dim * 2 / arraySize;
  83306. for (var i = 0; i < pos.length; i = i + 3) {
  83307. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  83308. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  83309. var y = -pos[i + 2] + minY;
  83310. if (!matrix[x]) {
  83311. matrix[x] = [];
  83312. }
  83313. if (!matrix[x][z]) {
  83314. matrix[x][z] = y;
  83315. }
  83316. matrix[x][z] = Math.max(y, matrix[x][z]);
  83317. }
  83318. for (var x = 0; x <= arraySize; ++x) {
  83319. if (!matrix[x]) {
  83320. var loc = 1;
  83321. while (!matrix[(x + loc) % arraySize]) {
  83322. loc++;
  83323. }
  83324. matrix[x] = matrix[(x + loc) % arraySize].slice();
  83325. //console.log("missing x", x);
  83326. }
  83327. for (var z = 0; z <= arraySize; ++z) {
  83328. if (!matrix[x][z]) {
  83329. var loc = 1;
  83330. var newValue;
  83331. while (newValue === undefined) {
  83332. newValue = matrix[x][(z + loc++) % arraySize];
  83333. }
  83334. matrix[x][z] = newValue;
  83335. }
  83336. }
  83337. }
  83338. var shape = new this.BJSCANNON.Heightfield(matrix, {
  83339. elementSize: elementSize
  83340. });
  83341. //For future reference, needed for body transformation
  83342. shape.minY = minY;
  83343. return shape;
  83344. };
  83345. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  83346. var object = impostor.object;
  83347. //make sure it is updated...
  83348. object.computeWorldMatrix && object.computeWorldMatrix(true);
  83349. // The delta between the mesh position and the mesh bounding box center
  83350. var bInfo = object.getBoundingInfo();
  83351. if (!bInfo)
  83352. return;
  83353. var center = impostor.getObjectCenter();
  83354. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  83355. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  83356. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  83357. this._tmpPosition.copyFrom(center);
  83358. var quaternion = object.rotationQuaternion;
  83359. if (!quaternion) {
  83360. return;
  83361. }
  83362. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  83363. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  83364. //-90 DEG in X, precalculated
  83365. quaternion = quaternion.multiply(this._minus90X);
  83366. //Invert! (Precalculated, 90 deg in X)
  83367. //No need to clone. this will never change.
  83368. impostor.setDeltaRotation(this._plus90X);
  83369. }
  83370. //If it is a heightfield, if should be centered.
  83371. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  83372. var mesh = object;
  83373. var boundingInfo = mesh.getBoundingInfo();
  83374. //calculate the correct body position:
  83375. var rotationQuaternion = mesh.rotationQuaternion;
  83376. mesh.rotationQuaternion = this._tmpUnityRotation;
  83377. mesh.computeWorldMatrix(true);
  83378. //get original center with no rotation
  83379. var c = center.clone();
  83380. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  83381. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  83382. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  83383. mesh.setPreTransformMatrix(p);
  83384. mesh.computeWorldMatrix(true);
  83385. //calculate the translation
  83386. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  83387. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  83388. //add it inverted to the delta
  83389. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  83390. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  83391. //rotation is back
  83392. mesh.rotationQuaternion = rotationQuaternion;
  83393. mesh.setPreTransformMatrix(oldPivot);
  83394. mesh.computeWorldMatrix(true);
  83395. }
  83396. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  83397. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  83398. //this._tmpPosition.copyFrom(object.position);
  83399. }
  83400. impostor.setDeltaPosition(this._tmpDeltaPosition);
  83401. //Now update the impostor object
  83402. impostor.physicsBody.position.copy(this._tmpPosition);
  83403. impostor.physicsBody.quaternion.copy(quaternion);
  83404. };
  83405. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  83406. impostor.object.position.copyFrom(impostor.physicsBody.position);
  83407. if (impostor.object.rotationQuaternion) {
  83408. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  83409. }
  83410. };
  83411. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  83412. impostor.physicsBody.position.copy(newPosition);
  83413. impostor.physicsBody.quaternion.copy(newRotation);
  83414. };
  83415. CannonJSPlugin.prototype.isSupported = function () {
  83416. return this.BJSCANNON !== undefined;
  83417. };
  83418. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  83419. impostor.physicsBody.velocity.copy(velocity);
  83420. };
  83421. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  83422. impostor.physicsBody.angularVelocity.copy(velocity);
  83423. };
  83424. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  83425. var v = impostor.physicsBody.velocity;
  83426. if (!v) {
  83427. return null;
  83428. }
  83429. return new BABYLON.Vector3(v.x, v.y, v.z);
  83430. };
  83431. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  83432. var v = impostor.physicsBody.angularVelocity;
  83433. if (!v) {
  83434. return null;
  83435. }
  83436. return new BABYLON.Vector3(v.x, v.y, v.z);
  83437. };
  83438. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  83439. impostor.physicsBody.mass = mass;
  83440. impostor.physicsBody.updateMassProperties();
  83441. };
  83442. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  83443. return impostor.physicsBody.mass;
  83444. };
  83445. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  83446. return impostor.physicsBody.material.friction;
  83447. };
  83448. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  83449. impostor.physicsBody.material.friction = friction;
  83450. };
  83451. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  83452. return impostor.physicsBody.material.restitution;
  83453. };
  83454. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  83455. impostor.physicsBody.material.restitution = restitution;
  83456. };
  83457. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  83458. impostor.physicsBody.sleep();
  83459. };
  83460. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  83461. impostor.physicsBody.wakeUp();
  83462. };
  83463. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  83464. joint.physicsJoint.distance = maxDistance;
  83465. };
  83466. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  83467. // if (!motorIndex) {
  83468. // joint.physicsJoint.enableMotor();
  83469. // }
  83470. // }
  83471. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  83472. // if (!motorIndex) {
  83473. // joint.physicsJoint.disableMotor();
  83474. // }
  83475. // }
  83476. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  83477. if (!motorIndex) {
  83478. joint.physicsJoint.enableMotor();
  83479. joint.physicsJoint.setMotorSpeed(speed);
  83480. if (maxForce) {
  83481. this.setLimit(joint, maxForce);
  83482. }
  83483. }
  83484. };
  83485. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  83486. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  83487. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  83488. };
  83489. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  83490. var body = impostor.physicsBody;
  83491. mesh.position.x = body.position.x;
  83492. mesh.position.y = body.position.y;
  83493. mesh.position.z = body.position.z;
  83494. if (mesh.rotationQuaternion) {
  83495. mesh.rotationQuaternion.x = body.quaternion.x;
  83496. mesh.rotationQuaternion.y = body.quaternion.y;
  83497. mesh.rotationQuaternion.z = body.quaternion.z;
  83498. mesh.rotationQuaternion.w = body.quaternion.w;
  83499. }
  83500. };
  83501. CannonJSPlugin.prototype.getRadius = function (impostor) {
  83502. var shape = impostor.physicsBody.shapes[0];
  83503. return shape.boundingSphereRadius;
  83504. };
  83505. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  83506. var shape = impostor.physicsBody.shapes[0];
  83507. result.x = shape.halfExtents.x * 2;
  83508. result.y = shape.halfExtents.y * 2;
  83509. result.z = shape.halfExtents.z * 2;
  83510. };
  83511. CannonJSPlugin.prototype.dispose = function () {
  83512. };
  83513. CannonJSPlugin.prototype._extendNamespace = function () {
  83514. //this will force cannon to execute at least one step when using interpolation
  83515. var step_tmp1 = new this.BJSCANNON.Vec3();
  83516. var Engine = this.BJSCANNON;
  83517. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  83518. maxSubSteps = maxSubSteps || 10;
  83519. timeSinceLastCalled = timeSinceLastCalled || 0;
  83520. if (timeSinceLastCalled === 0) {
  83521. this.internalStep(dt);
  83522. this.time += dt;
  83523. }
  83524. else {
  83525. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  83526. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  83527. var t0 = performance.now();
  83528. for (var i = 0; i !== internalSteps; i++) {
  83529. this.internalStep(dt);
  83530. if (performance.now() - t0 > dt * 1000) {
  83531. break;
  83532. }
  83533. }
  83534. this.time += timeSinceLastCalled;
  83535. var h = this.time % dt;
  83536. var h_div_dt = h / dt;
  83537. var interpvelo = step_tmp1;
  83538. var bodies = this.bodies;
  83539. for (var j = 0; j !== bodies.length; j++) {
  83540. var b = bodies[j];
  83541. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  83542. b.position.vsub(b.previousPosition, interpvelo);
  83543. interpvelo.scale(h_div_dt, interpvelo);
  83544. b.position.vadd(interpvelo, b.interpolatedPosition);
  83545. }
  83546. else {
  83547. b.interpolatedPosition.copy(b.position);
  83548. b.interpolatedQuaternion.copy(b.quaternion);
  83549. }
  83550. }
  83551. }
  83552. };
  83553. };
  83554. return CannonJSPlugin;
  83555. }());
  83556. BABYLON.CannonJSPlugin = CannonJSPlugin;
  83557. })(BABYLON || (BABYLON = {}));
  83558. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  83559. var BABYLON;
  83560. (function (BABYLON) {
  83561. var OimoJSPlugin = /** @class */ (function () {
  83562. function OimoJSPlugin(iterations) {
  83563. this.name = "OimoJSPlugin";
  83564. this._tmpImpostorsArray = [];
  83565. this._tmpPositionVector = BABYLON.Vector3.Zero();
  83566. this.BJSOIMO = OIMO;
  83567. this.world = new this.BJSOIMO.World({
  83568. iterations: iterations
  83569. });
  83570. this.world.clear();
  83571. }
  83572. OimoJSPlugin.prototype.setGravity = function (gravity) {
  83573. this.world.gravity.copy(gravity);
  83574. };
  83575. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  83576. this.world.timeStep = timeStep;
  83577. };
  83578. OimoJSPlugin.prototype.getTimeStep = function () {
  83579. return this.world.timeStep;
  83580. };
  83581. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  83582. var _this = this;
  83583. impostors.forEach(function (impostor) {
  83584. impostor.beforeStep();
  83585. });
  83586. this.world.step();
  83587. impostors.forEach(function (impostor) {
  83588. impostor.afterStep();
  83589. //update the ordered impostors array
  83590. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  83591. });
  83592. //check for collisions
  83593. var contact = this.world.contacts;
  83594. while (contact !== null) {
  83595. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  83596. contact = contact.next;
  83597. continue;
  83598. }
  83599. //is this body colliding with any other? get the impostor
  83600. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  83601. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  83602. if (!mainImpostor || !collidingImpostor) {
  83603. contact = contact.next;
  83604. continue;
  83605. }
  83606. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  83607. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  83608. contact = contact.next;
  83609. }
  83610. };
  83611. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  83612. var mass = impostor.physicsBody.mass;
  83613. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  83614. };
  83615. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  83616. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  83617. this.applyImpulse(impostor, force, contactPoint);
  83618. };
  83619. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  83620. var _this = this;
  83621. //parent-child relationship. Does this impostor has a parent impostor?
  83622. if (impostor.parent) {
  83623. if (impostor.physicsBody) {
  83624. this.removePhysicsBody(impostor);
  83625. //TODO is that needed?
  83626. impostor.forceUpdate();
  83627. }
  83628. return;
  83629. }
  83630. if (impostor.isBodyInitRequired()) {
  83631. var bodyConfig = {
  83632. name: impostor.uniqueId,
  83633. //Oimo must have mass, also for static objects.
  83634. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  83635. size: [],
  83636. type: [],
  83637. pos: [],
  83638. posShape: [],
  83639. rot: [],
  83640. rotShape: [],
  83641. move: impostor.getParam("mass") !== 0,
  83642. density: impostor.getParam("mass"),
  83643. friction: impostor.getParam("friction"),
  83644. restitution: impostor.getParam("restitution"),
  83645. //Supporting older versions of Oimo
  83646. world: this.world
  83647. };
  83648. var impostors = [impostor];
  83649. var addToArray = function (parent) {
  83650. if (!parent.getChildMeshes)
  83651. return;
  83652. parent.getChildMeshes().forEach(function (m) {
  83653. if (m.physicsImpostor) {
  83654. impostors.push(m.physicsImpostor);
  83655. //m.physicsImpostor._init();
  83656. }
  83657. });
  83658. };
  83659. addToArray(impostor.object);
  83660. var checkWithEpsilon_1 = function (value) {
  83661. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  83662. };
  83663. impostors.forEach(function (i) {
  83664. if (!i.object.rotationQuaternion) {
  83665. return;
  83666. }
  83667. //get the correct bounding box
  83668. var oldQuaternion = i.object.rotationQuaternion;
  83669. var rot = oldQuaternion.toEulerAngles();
  83670. var extendSize = i.getObjectExtendSize();
  83671. var radToDeg = 57.295779513082320876;
  83672. if (i === impostor) {
  83673. var center = impostor.getObjectCenter();
  83674. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  83675. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  83676. //Can also use Array.prototype.push.apply
  83677. bodyConfig.pos.push(center.x);
  83678. bodyConfig.pos.push(center.y);
  83679. bodyConfig.pos.push(center.z);
  83680. bodyConfig.posShape.push(0, 0, 0);
  83681. //tmp solution
  83682. bodyConfig.rot.push(rot.x * radToDeg);
  83683. bodyConfig.rot.push(rot.y * radToDeg);
  83684. bodyConfig.rot.push(rot.z * radToDeg);
  83685. bodyConfig.rotShape.push(0, 0, 0);
  83686. }
  83687. else {
  83688. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  83689. bodyConfig.posShape.push(localPosition.x);
  83690. bodyConfig.posShape.push(localPosition.y);
  83691. bodyConfig.posShape.push(localPosition.z);
  83692. bodyConfig.pos.push(0, 0, 0);
  83693. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  83694. bodyConfig.rot.push(0);
  83695. bodyConfig.rot.push(0);
  83696. bodyConfig.rot.push(0);
  83697. bodyConfig.rotShape.push(rot.x * radToDeg);
  83698. bodyConfig.rotShape.push(rot.y * radToDeg);
  83699. bodyConfig.rotShape.push(rot.z * radToDeg);
  83700. }
  83701. // register mesh
  83702. switch (i.type) {
  83703. case BABYLON.PhysicsImpostor.ParticleImpostor:
  83704. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  83705. case BABYLON.PhysicsImpostor.SphereImpostor:
  83706. var radiusX = extendSize.x;
  83707. var radiusY = extendSize.y;
  83708. var radiusZ = extendSize.z;
  83709. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  83710. bodyConfig.type.push('sphere');
  83711. //due to the way oimo works with compounds, add 3 times
  83712. bodyConfig.size.push(size);
  83713. bodyConfig.size.push(size);
  83714. bodyConfig.size.push(size);
  83715. break;
  83716. case BABYLON.PhysicsImpostor.CylinderImpostor:
  83717. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  83718. var sizeY = checkWithEpsilon_1(extendSize.y);
  83719. bodyConfig.type.push('cylinder');
  83720. bodyConfig.size.push(sizeX);
  83721. bodyConfig.size.push(sizeY);
  83722. //due to the way oimo works with compounds, add one more value.
  83723. bodyConfig.size.push(sizeY);
  83724. break;
  83725. case BABYLON.PhysicsImpostor.PlaneImpostor:
  83726. case BABYLON.PhysicsImpostor.BoxImpostor:
  83727. default:
  83728. var sizeX = checkWithEpsilon_1(extendSize.x);
  83729. var sizeY = checkWithEpsilon_1(extendSize.y);
  83730. var sizeZ = checkWithEpsilon_1(extendSize.z);
  83731. bodyConfig.type.push('box');
  83732. //if (i === impostor) {
  83733. bodyConfig.size.push(sizeX);
  83734. bodyConfig.size.push(sizeY);
  83735. bodyConfig.size.push(sizeZ);
  83736. //} else {
  83737. // bodyConfig.size.push(0,0,0);
  83738. //}
  83739. break;
  83740. }
  83741. //actually not needed, but hey...
  83742. i.object.rotationQuaternion = oldQuaternion;
  83743. });
  83744. impostor.physicsBody = this.world.add(bodyConfig);
  83745. }
  83746. else {
  83747. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  83748. }
  83749. impostor.setDeltaPosition(this._tmpPositionVector);
  83750. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  83751. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  83752. };
  83753. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  83754. //impostor.physicsBody.dispose();
  83755. //Same as : (older oimo versions)
  83756. this.world.removeRigidBody(impostor.physicsBody);
  83757. };
  83758. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  83759. var mainBody = impostorJoint.mainImpostor.physicsBody;
  83760. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  83761. if (!mainBody || !connectedBody) {
  83762. return;
  83763. }
  83764. var jointData = impostorJoint.joint.jointData;
  83765. var options = jointData.nativeParams || {};
  83766. var type;
  83767. var nativeJointData = {
  83768. body1: mainBody,
  83769. body2: connectedBody,
  83770. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  83771. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  83772. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  83773. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  83774. min: options.min,
  83775. max: options.max,
  83776. collision: options.collision || jointData.collision,
  83777. spring: options.spring,
  83778. //supporting older version of Oimo
  83779. world: this.world
  83780. };
  83781. switch (impostorJoint.joint.type) {
  83782. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  83783. type = "jointBall";
  83784. break;
  83785. case BABYLON.PhysicsJoint.SpringJoint:
  83786. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  83787. var springData = jointData;
  83788. nativeJointData.min = springData.length || nativeJointData.min;
  83789. //Max should also be set, just make sure it is at least min
  83790. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  83791. case BABYLON.PhysicsJoint.DistanceJoint:
  83792. type = "jointDistance";
  83793. nativeJointData.max = jointData.maxDistance;
  83794. break;
  83795. case BABYLON.PhysicsJoint.PrismaticJoint:
  83796. type = "jointPrisme";
  83797. break;
  83798. case BABYLON.PhysicsJoint.SliderJoint:
  83799. type = "jointSlide";
  83800. break;
  83801. case BABYLON.PhysicsJoint.WheelJoint:
  83802. type = "jointWheel";
  83803. break;
  83804. case BABYLON.PhysicsJoint.HingeJoint:
  83805. default:
  83806. type = "jointHinge";
  83807. break;
  83808. }
  83809. nativeJointData.type = type;
  83810. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  83811. };
  83812. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  83813. //Bug in Oimo prevents us from disposing a joint in the playground
  83814. //joint.joint.physicsJoint.dispose();
  83815. //So we will bruteforce it!
  83816. try {
  83817. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  83818. }
  83819. catch (e) {
  83820. BABYLON.Tools.Warn(e);
  83821. }
  83822. };
  83823. OimoJSPlugin.prototype.isSupported = function () {
  83824. return this.BJSOIMO !== undefined;
  83825. };
  83826. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  83827. if (!impostor.physicsBody.sleeping) {
  83828. //TODO check that
  83829. /*if (impostor.physicsBody.shapes.next) {
  83830. var parentShape = this._getLastShape(impostor.physicsBody);
  83831. impostor.object.position.copyFrom(parentShape.position);
  83832. console.log(parentShape.position);
  83833. } else {*/
  83834. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  83835. //}
  83836. if (impostor.object.rotationQuaternion) {
  83837. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  83838. }
  83839. }
  83840. };
  83841. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  83842. var body = impostor.physicsBody;
  83843. body.position.copy(newPosition);
  83844. body.orientation.copy(newRotation);
  83845. body.syncShapes();
  83846. body.awake();
  83847. };
  83848. /*private _getLastShape(body: any): any {
  83849. var lastShape = body.shapes;
  83850. while (lastShape.next) {
  83851. lastShape = lastShape.next;
  83852. }
  83853. return lastShape;
  83854. }*/
  83855. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  83856. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  83857. };
  83858. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  83859. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  83860. };
  83861. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  83862. var v = impostor.physicsBody.linearVelocity;
  83863. if (!v) {
  83864. return null;
  83865. }
  83866. return new BABYLON.Vector3(v.x, v.y, v.z);
  83867. };
  83868. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  83869. var v = impostor.physicsBody.angularVelocity;
  83870. if (!v) {
  83871. return null;
  83872. }
  83873. return new BABYLON.Vector3(v.x, v.y, v.z);
  83874. };
  83875. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  83876. var staticBody = mass === 0;
  83877. //this will actually set the body's density and not its mass.
  83878. //But this is how oimo treats the mass variable.
  83879. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  83880. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  83881. };
  83882. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  83883. return impostor.physicsBody.shapes.density;
  83884. };
  83885. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  83886. return impostor.physicsBody.shapes.friction;
  83887. };
  83888. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  83889. impostor.physicsBody.shapes.friction = friction;
  83890. };
  83891. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  83892. return impostor.physicsBody.shapes.restitution;
  83893. };
  83894. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  83895. impostor.physicsBody.shapes.restitution = restitution;
  83896. };
  83897. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  83898. impostor.physicsBody.sleep();
  83899. };
  83900. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  83901. impostor.physicsBody.awake();
  83902. };
  83903. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  83904. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  83905. if (minDistance !== void 0) {
  83906. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  83907. }
  83908. };
  83909. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  83910. //TODO separate rotational and transational motors.
  83911. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  83912. if (motor) {
  83913. motor.setMotor(speed, maxForce);
  83914. }
  83915. };
  83916. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  83917. //TODO separate rotational and transational motors.
  83918. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  83919. if (motor) {
  83920. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  83921. }
  83922. };
  83923. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  83924. var body = impostor.physicsBody;
  83925. mesh.position.x = body.position.x;
  83926. mesh.position.y = body.position.y;
  83927. mesh.position.z = body.position.z;
  83928. if (mesh.rotationQuaternion) {
  83929. mesh.rotationQuaternion.x = body.orientation.x;
  83930. mesh.rotationQuaternion.y = body.orientation.y;
  83931. mesh.rotationQuaternion.z = body.orientation.z;
  83932. mesh.rotationQuaternion.w = body.orientation.s;
  83933. }
  83934. };
  83935. OimoJSPlugin.prototype.getRadius = function (impostor) {
  83936. return impostor.physicsBody.shapes.radius;
  83937. };
  83938. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  83939. var shape = impostor.physicsBody.shapes;
  83940. result.x = shape.halfWidth * 2;
  83941. result.y = shape.halfHeight * 2;
  83942. result.z = shape.halfDepth * 2;
  83943. };
  83944. OimoJSPlugin.prototype.dispose = function () {
  83945. this.world.clear();
  83946. };
  83947. return OimoJSPlugin;
  83948. }());
  83949. BABYLON.OimoJSPlugin = OimoJSPlugin;
  83950. })(BABYLON || (BABYLON = {}));
  83951. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  83952. var BABYLON;
  83953. (function (BABYLON) {
  83954. /*
  83955. * Based on jsTGALoader - Javascript loader for TGA file
  83956. * By Vincent Thibault
  83957. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  83958. */
  83959. var TGATools = /** @class */ (function () {
  83960. function TGATools() {
  83961. }
  83962. TGATools.GetTGAHeader = function (data) {
  83963. var offset = 0;
  83964. var header = {
  83965. id_length: data[offset++],
  83966. colormap_type: data[offset++],
  83967. image_type: data[offset++],
  83968. colormap_index: data[offset++] | data[offset++] << 8,
  83969. colormap_length: data[offset++] | data[offset++] << 8,
  83970. colormap_size: data[offset++],
  83971. origin: [
  83972. data[offset++] | data[offset++] << 8,
  83973. data[offset++] | data[offset++] << 8
  83974. ],
  83975. width: data[offset++] | data[offset++] << 8,
  83976. height: data[offset++] | data[offset++] << 8,
  83977. pixel_size: data[offset++],
  83978. flags: data[offset++]
  83979. };
  83980. return header;
  83981. };
  83982. TGATools.UploadContent = function (gl, data) {
  83983. // Not enough data to contain header ?
  83984. if (data.length < 19) {
  83985. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  83986. return;
  83987. }
  83988. // Read Header
  83989. var offset = 18;
  83990. var header = TGATools.GetTGAHeader(data);
  83991. // Assume it's a valid Targa file.
  83992. if (header.id_length + offset > data.length) {
  83993. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  83994. return;
  83995. }
  83996. // Skip not needed data
  83997. offset += header.id_length;
  83998. var use_rle = false;
  83999. var use_pal = false;
  84000. var use_grey = false;
  84001. // Get some informations.
  84002. switch (header.image_type) {
  84003. case TGATools._TYPE_RLE_INDEXED:
  84004. use_rle = true;
  84005. case TGATools._TYPE_INDEXED:
  84006. use_pal = true;
  84007. break;
  84008. case TGATools._TYPE_RLE_RGB:
  84009. use_rle = true;
  84010. case TGATools._TYPE_RGB:
  84011. // use_rgb = true;
  84012. break;
  84013. case TGATools._TYPE_RLE_GREY:
  84014. use_rle = true;
  84015. case TGATools._TYPE_GREY:
  84016. use_grey = true;
  84017. break;
  84018. }
  84019. var pixel_data;
  84020. // var numAlphaBits = header.flags & 0xf;
  84021. var pixel_size = header.pixel_size >> 3;
  84022. var pixel_total = header.width * header.height * pixel_size;
  84023. // Read palettes
  84024. var palettes;
  84025. if (use_pal) {
  84026. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  84027. }
  84028. // Read LRE
  84029. if (use_rle) {
  84030. pixel_data = new Uint8Array(pixel_total);
  84031. var c, count, i;
  84032. var localOffset = 0;
  84033. var pixels = new Uint8Array(pixel_size);
  84034. while (offset < pixel_total && localOffset < pixel_total) {
  84035. c = data[offset++];
  84036. count = (c & 0x7f) + 1;
  84037. // RLE pixels
  84038. if (c & 0x80) {
  84039. // Bind pixel tmp array
  84040. for (i = 0; i < pixel_size; ++i) {
  84041. pixels[i] = data[offset++];
  84042. }
  84043. // Copy pixel array
  84044. for (i = 0; i < count; ++i) {
  84045. pixel_data.set(pixels, localOffset + i * pixel_size);
  84046. }
  84047. localOffset += pixel_size * count;
  84048. }
  84049. // Raw pixels
  84050. else {
  84051. count *= pixel_size;
  84052. for (i = 0; i < count; ++i) {
  84053. pixel_data[localOffset + i] = data[offset++];
  84054. }
  84055. localOffset += count;
  84056. }
  84057. }
  84058. }
  84059. // RAW Pixels
  84060. else {
  84061. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  84062. }
  84063. // Load to texture
  84064. var x_start, y_start, x_step, y_step, y_end, x_end;
  84065. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  84066. default:
  84067. case TGATools._ORIGIN_UL:
  84068. x_start = 0;
  84069. x_step = 1;
  84070. x_end = header.width;
  84071. y_start = 0;
  84072. y_step = 1;
  84073. y_end = header.height;
  84074. break;
  84075. case TGATools._ORIGIN_BL:
  84076. x_start = 0;
  84077. x_step = 1;
  84078. x_end = header.width;
  84079. y_start = header.height - 1;
  84080. y_step = -1;
  84081. y_end = -1;
  84082. break;
  84083. case TGATools._ORIGIN_UR:
  84084. x_start = header.width - 1;
  84085. x_step = -1;
  84086. x_end = -1;
  84087. y_start = 0;
  84088. y_step = 1;
  84089. y_end = header.height;
  84090. break;
  84091. case TGATools._ORIGIN_BR:
  84092. x_start = header.width - 1;
  84093. x_step = -1;
  84094. x_end = -1;
  84095. y_start = header.height - 1;
  84096. y_step = -1;
  84097. y_end = -1;
  84098. break;
  84099. }
  84100. // Load the specify method
  84101. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  84102. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  84103. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  84104. };
  84105. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84106. var image = pixel_data, colormap = palettes;
  84107. var width = header.width, height = header.height;
  84108. var color, i = 0, x, y;
  84109. var imageData = new Uint8Array(width * height * 4);
  84110. for (y = y_start; y !== y_end; y += y_step) {
  84111. for (x = x_start; x !== x_end; x += x_step, i++) {
  84112. color = image[i];
  84113. imageData[(x + width * y) * 4 + 3] = 255;
  84114. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  84115. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  84116. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  84117. }
  84118. }
  84119. return imageData;
  84120. };
  84121. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84122. var image = pixel_data;
  84123. var width = header.width, height = header.height;
  84124. var color, i = 0, x, y;
  84125. var imageData = new Uint8Array(width * height * 4);
  84126. for (y = y_start; y !== y_end; y += y_step) {
  84127. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  84128. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  84129. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  84130. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  84131. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  84132. imageData[(x + width * y) * 4 + 0] = r;
  84133. imageData[(x + width * y) * 4 + 1] = g;
  84134. imageData[(x + width * y) * 4 + 2] = b;
  84135. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  84136. }
  84137. }
  84138. return imageData;
  84139. };
  84140. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84141. var image = pixel_data;
  84142. var width = header.width, height = header.height;
  84143. var i = 0, x, y;
  84144. var imageData = new Uint8Array(width * height * 4);
  84145. for (y = y_start; y !== y_end; y += y_step) {
  84146. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  84147. imageData[(x + width * y) * 4 + 3] = 255;
  84148. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  84149. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  84150. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  84151. }
  84152. }
  84153. return imageData;
  84154. };
  84155. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84156. var image = pixel_data;
  84157. var width = header.width, height = header.height;
  84158. var i = 0, x, y;
  84159. var imageData = new Uint8Array(width * height * 4);
  84160. for (y = y_start; y !== y_end; y += y_step) {
  84161. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  84162. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  84163. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  84164. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  84165. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  84166. }
  84167. }
  84168. return imageData;
  84169. };
  84170. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84171. var image = pixel_data;
  84172. var width = header.width, height = header.height;
  84173. var color, i = 0, x, y;
  84174. var imageData = new Uint8Array(width * height * 4);
  84175. for (y = y_start; y !== y_end; y += y_step) {
  84176. for (x = x_start; x !== x_end; x += x_step, i++) {
  84177. color = image[i];
  84178. imageData[(x + width * y) * 4 + 0] = color;
  84179. imageData[(x + width * y) * 4 + 1] = color;
  84180. imageData[(x + width * y) * 4 + 2] = color;
  84181. imageData[(x + width * y) * 4 + 3] = 255;
  84182. }
  84183. }
  84184. return imageData;
  84185. };
  84186. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84187. var image = pixel_data;
  84188. var width = header.width, height = header.height;
  84189. var i = 0, x, y;
  84190. var imageData = new Uint8Array(width * height * 4);
  84191. for (y = y_start; y !== y_end; y += y_step) {
  84192. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  84193. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  84194. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  84195. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  84196. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  84197. }
  84198. }
  84199. return imageData;
  84200. };
  84201. //private static _TYPE_NO_DATA = 0;
  84202. TGATools._TYPE_INDEXED = 1;
  84203. TGATools._TYPE_RGB = 2;
  84204. TGATools._TYPE_GREY = 3;
  84205. TGATools._TYPE_RLE_INDEXED = 9;
  84206. TGATools._TYPE_RLE_RGB = 10;
  84207. TGATools._TYPE_RLE_GREY = 11;
  84208. TGATools._ORIGIN_MASK = 0x30;
  84209. TGATools._ORIGIN_SHIFT = 0x04;
  84210. TGATools._ORIGIN_BL = 0x00;
  84211. TGATools._ORIGIN_BR = 0x01;
  84212. TGATools._ORIGIN_UL = 0x02;
  84213. TGATools._ORIGIN_UR = 0x03;
  84214. return TGATools;
  84215. }());
  84216. BABYLON.TGATools = TGATools;
  84217. })(BABYLON || (BABYLON = {}));
  84218. //# sourceMappingURL=babylon.tga.js.map
  84219. var BABYLON;
  84220. (function (BABYLON) {
  84221. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  84222. // All values and structures referenced from:
  84223. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  84224. var DDS_MAGIC = 0x20534444;
  84225. var
  84226. //DDSD_CAPS = 0x1,
  84227. //DDSD_HEIGHT = 0x2,
  84228. //DDSD_WIDTH = 0x4,
  84229. //DDSD_PITCH = 0x8,
  84230. //DDSD_PIXELFORMAT = 0x1000,
  84231. DDSD_MIPMAPCOUNT = 0x20000;
  84232. //DDSD_LINEARSIZE = 0x80000,
  84233. //DDSD_DEPTH = 0x800000;
  84234. // var DDSCAPS_COMPLEX = 0x8,
  84235. // DDSCAPS_MIPMAP = 0x400000,
  84236. // DDSCAPS_TEXTURE = 0x1000;
  84237. var DDSCAPS2_CUBEMAP = 0x200;
  84238. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  84239. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  84240. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  84241. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  84242. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  84243. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  84244. // DDSCAPS2_VOLUME = 0x200000;
  84245. var
  84246. //DDPF_ALPHAPIXELS = 0x1,
  84247. //DDPF_ALPHA = 0x2,
  84248. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  84249. //DDPF_YUV = 0x200,
  84250. DDPF_LUMINANCE = 0x20000;
  84251. function FourCCToInt32(value) {
  84252. return value.charCodeAt(0) +
  84253. (value.charCodeAt(1) << 8) +
  84254. (value.charCodeAt(2) << 16) +
  84255. (value.charCodeAt(3) << 24);
  84256. }
  84257. function Int32ToFourCC(value) {
  84258. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  84259. }
  84260. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  84261. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  84262. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  84263. var FOURCC_DX10 = FourCCToInt32("DX10");
  84264. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  84265. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  84266. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  84267. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  84268. var headerLengthInt = 31; // The header length in 32 bit ints
  84269. // Offsets into the header array
  84270. var off_magic = 0;
  84271. var off_size = 1;
  84272. var off_flags = 2;
  84273. var off_height = 3;
  84274. var off_width = 4;
  84275. var off_mipmapCount = 7;
  84276. var off_pfFlags = 20;
  84277. var off_pfFourCC = 21;
  84278. var off_RGBbpp = 22;
  84279. var off_RMask = 23;
  84280. var off_GMask = 24;
  84281. var off_BMask = 25;
  84282. var off_AMask = 26;
  84283. // var off_caps1 = 27;
  84284. var off_caps2 = 28;
  84285. // var off_caps3 = 29;
  84286. // var off_caps4 = 30;
  84287. var off_dxgiFormat = 32;
  84288. ;
  84289. var DDSTools = /** @class */ (function () {
  84290. function DDSTools() {
  84291. }
  84292. DDSTools.GetDDSInfo = function (arrayBuffer) {
  84293. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  84294. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  84295. var mipmapCount = 1;
  84296. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  84297. mipmapCount = Math.max(1, header[off_mipmapCount]);
  84298. }
  84299. var fourCC = header[off_pfFourCC];
  84300. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  84301. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  84302. switch (fourCC) {
  84303. case FOURCC_D3DFMT_R16G16B16A16F:
  84304. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  84305. break;
  84306. case FOURCC_D3DFMT_R32G32B32A32F:
  84307. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  84308. break;
  84309. case FOURCC_DX10:
  84310. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  84311. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  84312. break;
  84313. }
  84314. }
  84315. return {
  84316. width: header[off_width],
  84317. height: header[off_height],
  84318. mipmapCount: mipmapCount,
  84319. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  84320. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  84321. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  84322. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  84323. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  84324. dxgiFormat: dxgiFormat,
  84325. textureType: textureType
  84326. };
  84327. };
  84328. DDSTools._ToHalfFloat = function (value) {
  84329. if (!DDSTools._FloatView) {
  84330. DDSTools._FloatView = new Float32Array(1);
  84331. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  84332. }
  84333. DDSTools._FloatView[0] = value;
  84334. var x = DDSTools._Int32View[0];
  84335. var bits = (x >> 16) & 0x8000; /* Get the sign */
  84336. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  84337. var e = (x >> 23) & 0xff; /* Using int is faster here */
  84338. /* If zero, or denormal, or exponent underflows too much for a denormal
  84339. * half, return signed zero. */
  84340. if (e < 103) {
  84341. return bits;
  84342. }
  84343. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  84344. if (e > 142) {
  84345. bits |= 0x7c00;
  84346. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  84347. * not Inf, so make sure we set one mantissa bit too. */
  84348. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  84349. return bits;
  84350. }
  84351. /* If exponent underflows but not too much, return a denormal */
  84352. if (e < 113) {
  84353. m |= 0x0800;
  84354. /* Extra rounding may overflow and set mantissa to 0 and exponent
  84355. * to 1, which is OK. */
  84356. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  84357. return bits;
  84358. }
  84359. bits |= ((e - 112) << 10) | (m >> 1);
  84360. bits += m & 1;
  84361. return bits;
  84362. };
  84363. DDSTools._FromHalfFloat = function (value) {
  84364. var s = (value & 0x8000) >> 15;
  84365. var e = (value & 0x7C00) >> 10;
  84366. var f = value & 0x03FF;
  84367. if (e === 0) {
  84368. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  84369. }
  84370. else if (e == 0x1F) {
  84371. return f ? NaN : ((s ? -1 : 1) * Infinity);
  84372. }
  84373. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  84374. };
  84375. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84376. var destArray = new Float32Array(dataLength);
  84377. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  84378. var index = 0;
  84379. for (var y = 0; y < height; y++) {
  84380. for (var x = 0; x < width; x++) {
  84381. var srcPos = (x + y * width) * 4;
  84382. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  84383. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  84384. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  84385. if (DDSTools.StoreLODInAlphaChannel) {
  84386. destArray[index + 3] = lod;
  84387. }
  84388. else {
  84389. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  84390. }
  84391. index += 4;
  84392. }
  84393. }
  84394. return destArray;
  84395. };
  84396. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84397. if (DDSTools.StoreLODInAlphaChannel) {
  84398. var destArray = new Uint16Array(dataLength);
  84399. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  84400. var index = 0;
  84401. for (var y = 0; y < height; y++) {
  84402. for (var x = 0; x < width; x++) {
  84403. var srcPos = (x + y * width) * 4;
  84404. destArray[index] = srcData[srcPos];
  84405. destArray[index + 1] = srcData[srcPos + 1];
  84406. destArray[index + 2] = srcData[srcPos + 2];
  84407. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  84408. index += 4;
  84409. }
  84410. }
  84411. return destArray;
  84412. }
  84413. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  84414. };
  84415. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84416. if (DDSTools.StoreLODInAlphaChannel) {
  84417. var destArray = new Float32Array(dataLength);
  84418. var srcData = new Float32Array(arrayBuffer, dataOffset);
  84419. var index = 0;
  84420. for (var y = 0; y < height; y++) {
  84421. for (var x = 0; x < width; x++) {
  84422. var srcPos = (x + y * width) * 4;
  84423. destArray[index] = srcData[srcPos];
  84424. destArray[index + 1] = srcData[srcPos + 1];
  84425. destArray[index + 2] = srcData[srcPos + 2];
  84426. destArray[index + 3] = lod;
  84427. index += 4;
  84428. }
  84429. }
  84430. return destArray;
  84431. }
  84432. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  84433. };
  84434. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84435. var destArray = new Uint8Array(dataLength);
  84436. var srcData = new Float32Array(arrayBuffer, dataOffset);
  84437. var index = 0;
  84438. for (var y = 0; y < height; y++) {
  84439. for (var x = 0; x < width; x++) {
  84440. var srcPos = (x + y * width) * 4;
  84441. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  84442. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  84443. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  84444. if (DDSTools.StoreLODInAlphaChannel) {
  84445. destArray[index + 3] = lod;
  84446. }
  84447. else {
  84448. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  84449. }
  84450. index += 4;
  84451. }
  84452. }
  84453. return destArray;
  84454. };
  84455. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84456. var destArray = new Uint8Array(dataLength);
  84457. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  84458. var index = 0;
  84459. for (var y = 0; y < height; y++) {
  84460. for (var x = 0; x < width; x++) {
  84461. var srcPos = (x + y * width) * 4;
  84462. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  84463. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  84464. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  84465. if (DDSTools.StoreLODInAlphaChannel) {
  84466. destArray[index + 3] = lod;
  84467. }
  84468. else {
  84469. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  84470. }
  84471. index += 4;
  84472. }
  84473. }
  84474. return destArray;
  84475. };
  84476. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  84477. var byteArray = new Uint8Array(dataLength);
  84478. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  84479. var index = 0;
  84480. for (var y = 0; y < height; y++) {
  84481. for (var x = 0; x < width; x++) {
  84482. var srcPos = (x + y * width) * 4;
  84483. byteArray[index] = srcData[srcPos + rOffset];
  84484. byteArray[index + 1] = srcData[srcPos + gOffset];
  84485. byteArray[index + 2] = srcData[srcPos + bOffset];
  84486. byteArray[index + 3] = srcData[srcPos + aOffset];
  84487. index += 4;
  84488. }
  84489. }
  84490. return byteArray;
  84491. };
  84492. DDSTools._ExtractLongWordOrder = function (value) {
  84493. if (value === 0 || value === 255 || value === -16777216) {
  84494. return 0;
  84495. }
  84496. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  84497. };
  84498. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  84499. var byteArray = new Uint8Array(dataLength);
  84500. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  84501. var index = 0;
  84502. for (var y = 0; y < height; y++) {
  84503. for (var x = 0; x < width; x++) {
  84504. var srcPos = (x + y * width) * 3;
  84505. byteArray[index] = srcData[srcPos + rOffset];
  84506. byteArray[index + 1] = srcData[srcPos + gOffset];
  84507. byteArray[index + 2] = srcData[srcPos + bOffset];
  84508. index += 3;
  84509. }
  84510. }
  84511. return byteArray;
  84512. };
  84513. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  84514. var byteArray = new Uint8Array(dataLength);
  84515. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  84516. var index = 0;
  84517. for (var y = 0; y < height; y++) {
  84518. for (var x = 0; x < width; x++) {
  84519. var srcPos = (x + y * width);
  84520. byteArray[index] = srcData[srcPos];
  84521. index++;
  84522. }
  84523. }
  84524. return byteArray;
  84525. };
  84526. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  84527. if (lodIndex === void 0) { lodIndex = -1; }
  84528. var sphericalPolynomialFaces = null;
  84529. if (info.sphericalPolynomial) {
  84530. sphericalPolynomialFaces = new Array();
  84531. }
  84532. var ext = engine.getCaps().s3tc;
  84533. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  84534. var fourCC, width, height, dataLength = 0, dataOffset;
  84535. var byteArray, mipmapCount, mip;
  84536. var internalFormat = 0;
  84537. var format = 0;
  84538. var blockBytes = 1;
  84539. if (header[off_magic] !== DDS_MAGIC) {
  84540. BABYLON.Tools.Error("Invalid magic number in DDS header");
  84541. return;
  84542. }
  84543. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  84544. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  84545. return;
  84546. }
  84547. if (info.isCompressed && !ext) {
  84548. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  84549. return;
  84550. }
  84551. var bpp = header[off_RGBbpp];
  84552. dataOffset = header[off_size] + 4;
  84553. var computeFormats = false;
  84554. if (info.isFourCC) {
  84555. fourCC = header[off_pfFourCC];
  84556. switch (fourCC) {
  84557. case FOURCC_DXT1:
  84558. blockBytes = 8;
  84559. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  84560. break;
  84561. case FOURCC_DXT3:
  84562. blockBytes = 16;
  84563. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  84564. break;
  84565. case FOURCC_DXT5:
  84566. blockBytes = 16;
  84567. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  84568. break;
  84569. case FOURCC_D3DFMT_R16G16B16A16F:
  84570. computeFormats = true;
  84571. break;
  84572. case FOURCC_D3DFMT_R32G32B32A32F:
  84573. computeFormats = true;
  84574. break;
  84575. case FOURCC_DX10:
  84576. // There is an additionnal header so dataOffset need to be changed
  84577. dataOffset += 5 * 4; // 5 uints
  84578. var supported = false;
  84579. switch (info.dxgiFormat) {
  84580. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  84581. computeFormats = true;
  84582. supported = true;
  84583. break;
  84584. case DXGI_FORMAT_B8G8R8X8_UNORM:
  84585. info.isRGB = true;
  84586. info.isFourCC = false;
  84587. bpp = 32;
  84588. supported = true;
  84589. break;
  84590. }
  84591. if (supported) {
  84592. break;
  84593. }
  84594. default:
  84595. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  84596. return;
  84597. }
  84598. }
  84599. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  84600. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  84601. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  84602. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  84603. if (computeFormats) {
  84604. format = engine._getWebGLTextureType(info.textureType);
  84605. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  84606. }
  84607. mipmapCount = 1;
  84608. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  84609. mipmapCount = Math.max(1, header[off_mipmapCount]);
  84610. }
  84611. for (var face = 0; face < faces; face++) {
  84612. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  84613. width = header[off_width];
  84614. height = header[off_height];
  84615. for (mip = 0; mip < mipmapCount; ++mip) {
  84616. if (lodIndex === -1 || lodIndex === mip) {
  84617. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  84618. var i = (lodIndex === -1) ? mip : 0;
  84619. if (!info.isCompressed && info.isFourCC) {
  84620. dataLength = width * height * 4;
  84621. var floatArray = null;
  84622. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  84623. if (bpp === 128) {
  84624. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84625. if (sphericalPolynomialFaces && i == 0) {
  84626. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  84627. }
  84628. }
  84629. else if (bpp === 64) {
  84630. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84631. if (sphericalPolynomialFaces && i == 0) {
  84632. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  84633. }
  84634. }
  84635. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  84636. format = engine._getWebGLTextureType(info.textureType);
  84637. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  84638. }
  84639. else {
  84640. if (bpp === 128) {
  84641. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84642. if (sphericalPolynomialFaces && i == 0) {
  84643. sphericalPolynomialFaces.push(floatArray);
  84644. }
  84645. }
  84646. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  84647. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84648. if (sphericalPolynomialFaces && i == 0) {
  84649. sphericalPolynomialFaces.push(floatArray);
  84650. }
  84651. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  84652. format = engine._getWebGLTextureType(info.textureType);
  84653. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  84654. }
  84655. else { // 64
  84656. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84657. if (sphericalPolynomialFaces && i == 0) {
  84658. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  84659. }
  84660. }
  84661. }
  84662. if (floatArray) {
  84663. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  84664. }
  84665. }
  84666. else if (info.isRGB) {
  84667. if (bpp === 24) {
  84668. dataLength = width * height * 3;
  84669. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  84670. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  84671. }
  84672. else { // 32
  84673. dataLength = width * height * 4;
  84674. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  84675. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  84676. }
  84677. }
  84678. else if (info.isLuminance) {
  84679. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  84680. var unpaddedRowSize = width;
  84681. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  84682. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  84683. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  84684. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  84685. }
  84686. else {
  84687. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  84688. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  84689. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  84690. }
  84691. }
  84692. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  84693. width *= 0.5;
  84694. height *= 0.5;
  84695. width = Math.max(1.0, width);
  84696. height = Math.max(1.0, height);
  84697. }
  84698. if (currentFace !== undefined) {
  84699. // Loading a single face
  84700. break;
  84701. }
  84702. }
  84703. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  84704. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  84705. size: header[off_width],
  84706. right: sphericalPolynomialFaces[0],
  84707. left: sphericalPolynomialFaces[1],
  84708. up: sphericalPolynomialFaces[2],
  84709. down: sphericalPolynomialFaces[3],
  84710. front: sphericalPolynomialFaces[4],
  84711. back: sphericalPolynomialFaces[5],
  84712. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  84713. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  84714. gammaSpace: false,
  84715. });
  84716. }
  84717. else {
  84718. info.sphericalPolynomial = undefined;
  84719. }
  84720. };
  84721. DDSTools.StoreLODInAlphaChannel = false;
  84722. return DDSTools;
  84723. }());
  84724. BABYLON.DDSTools = DDSTools;
  84725. })(BABYLON || (BABYLON = {}));
  84726. //# sourceMappingURL=babylon.dds.js.map
  84727. var BABYLON;
  84728. (function (BABYLON) {
  84729. /**
  84730. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  84731. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  84732. */
  84733. var KhronosTextureContainer = /** @class */ (function () {
  84734. /**
  84735. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  84736. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  84737. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  84738. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  84739. */
  84740. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  84741. this.arrayBuffer = arrayBuffer;
  84742. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  84743. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  84744. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  84745. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  84746. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  84747. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  84748. BABYLON.Tools.Error("texture missing KTX identifier");
  84749. return;
  84750. }
  84751. // load the reset of the header in native 32 bit int
  84752. var header = new Int32Array(this.arrayBuffer, 12, 13);
  84753. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  84754. var oppositeEndianess = header[0] === 0x01020304;
  84755. // read all the header elements in order they exist in the file, without modification (sans endainness)
  84756. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  84757. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  84758. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  84759. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  84760. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  84761. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  84762. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  84763. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  84764. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  84765. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  84766. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  84767. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  84768. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  84769. if (this.glType !== 0) {
  84770. BABYLON.Tools.Error("only compressed formats currently supported");
  84771. return;
  84772. }
  84773. else {
  84774. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  84775. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  84776. }
  84777. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  84778. BABYLON.Tools.Error("only 2D textures currently supported");
  84779. return;
  84780. }
  84781. if (this.numberOfArrayElements !== 0) {
  84782. BABYLON.Tools.Error("texture arrays not currently supported");
  84783. return;
  84784. }
  84785. if (this.numberOfFaces !== facesExpected) {
  84786. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  84787. return;
  84788. }
  84789. // we now have a completely validated file, so could use existence of loadType as success
  84790. // would need to make this more elaborate & adjust checks above to support more than one load type
  84791. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  84792. }
  84793. // not as fast hardware based, but will probably never need to use
  84794. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  84795. return ((val & 0xFF) << 24)
  84796. | ((val & 0xFF00) << 8)
  84797. | ((val >> 8) & 0xFF00)
  84798. | ((val >> 24) & 0xFF);
  84799. };
  84800. /**
  84801. * It is assumed that the texture has already been created & is currently bound
  84802. */
  84803. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  84804. switch (this.loadType) {
  84805. case KhronosTextureContainer.COMPRESSED_2D:
  84806. this._upload2DCompressedLevels(gl, loadMipmaps);
  84807. break;
  84808. case KhronosTextureContainer.TEX_2D:
  84809. case KhronosTextureContainer.COMPRESSED_3D:
  84810. case KhronosTextureContainer.TEX_3D:
  84811. }
  84812. };
  84813. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  84814. // initialize width & height for level 1
  84815. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  84816. var width = this.pixelWidth;
  84817. var height = this.pixelHeight;
  84818. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  84819. for (var level = 0; level < mipmapCount; level++) {
  84820. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  84821. for (var face = 0; face < this.numberOfFaces; face++) {
  84822. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  84823. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  84824. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  84825. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  84826. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  84827. }
  84828. width = Math.max(1.0, width * 0.5);
  84829. height = Math.max(1.0, height * 0.5);
  84830. }
  84831. };
  84832. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  84833. // load types
  84834. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  84835. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  84836. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  84837. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  84838. return KhronosTextureContainer;
  84839. }());
  84840. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  84841. })(BABYLON || (BABYLON = {}));
  84842. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  84843. var BABYLON;
  84844. (function (BABYLON) {
  84845. var Debug;
  84846. (function (Debug) {
  84847. /**
  84848. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  84849. */
  84850. var SkeletonViewer = /** @class */ (function () {
  84851. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  84852. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  84853. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  84854. this.skeleton = skeleton;
  84855. this.mesh = mesh;
  84856. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  84857. this.renderingGroupId = renderingGroupId;
  84858. this.color = BABYLON.Color3.White();
  84859. this._debugLines = new Array();
  84860. this._isEnabled = false;
  84861. this._scene = scene;
  84862. this.update();
  84863. this._renderFunction = this.update.bind(this);
  84864. }
  84865. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  84866. get: function () {
  84867. return this._isEnabled;
  84868. },
  84869. set: function (value) {
  84870. if (this._isEnabled === value) {
  84871. return;
  84872. }
  84873. this._isEnabled = value;
  84874. if (value) {
  84875. this._scene.registerBeforeRender(this._renderFunction);
  84876. }
  84877. else {
  84878. this._scene.unregisterBeforeRender(this._renderFunction);
  84879. }
  84880. },
  84881. enumerable: true,
  84882. configurable: true
  84883. });
  84884. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  84885. if (x === void 0) { x = 0; }
  84886. if (y === void 0) { y = 0; }
  84887. if (z === void 0) { z = 0; }
  84888. var tmat = BABYLON.Tmp.Matrix[0];
  84889. var parentBone = bone.getParent();
  84890. tmat.copyFrom(bone.getLocalMatrix());
  84891. if (x !== 0 || y !== 0 || z !== 0) {
  84892. var tmat2 = BABYLON.Tmp.Matrix[1];
  84893. BABYLON.Matrix.IdentityToRef(tmat2);
  84894. tmat2.m[12] = x;
  84895. tmat2.m[13] = y;
  84896. tmat2.m[14] = z;
  84897. tmat2.multiplyToRef(tmat, tmat);
  84898. }
  84899. if (parentBone) {
  84900. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  84901. }
  84902. tmat.multiplyToRef(meshMat, tmat);
  84903. position.x = tmat.m[12];
  84904. position.y = tmat.m[13];
  84905. position.z = tmat.m[14];
  84906. };
  84907. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  84908. var len = bones.length;
  84909. var meshPos = this.mesh.position;
  84910. for (var i = 0; i < len; i++) {
  84911. var bone = bones[i];
  84912. var points = this._debugLines[i];
  84913. if (!points) {
  84914. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84915. this._debugLines[i] = points;
  84916. }
  84917. this._getBonePosition(points[0], bone, meshMat);
  84918. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  84919. points[0].subtractInPlace(meshPos);
  84920. points[1].subtractInPlace(meshPos);
  84921. }
  84922. };
  84923. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  84924. var len = bones.length;
  84925. var boneNum = 0;
  84926. var meshPos = this.mesh.position;
  84927. for (var i = len - 1; i >= 0; i--) {
  84928. var childBone = bones[i];
  84929. var parentBone = childBone.getParent();
  84930. if (!parentBone) {
  84931. continue;
  84932. }
  84933. var points = this._debugLines[boneNum];
  84934. if (!points) {
  84935. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84936. this._debugLines[boneNum] = points;
  84937. }
  84938. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  84939. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  84940. points[0].subtractInPlace(meshPos);
  84941. points[1].subtractInPlace(meshPos);
  84942. boneNum++;
  84943. }
  84944. };
  84945. SkeletonViewer.prototype.update = function () {
  84946. if (this.autoUpdateBonesMatrices) {
  84947. this.skeleton.computeAbsoluteTransforms();
  84948. }
  84949. if (this.skeleton.bones[0].length === undefined) {
  84950. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  84951. }
  84952. else {
  84953. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  84954. }
  84955. if (!this._debugMesh) {
  84956. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  84957. this._debugMesh.renderingGroupId = this.renderingGroupId;
  84958. }
  84959. else {
  84960. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  84961. }
  84962. this._debugMesh.position.copyFrom(this.mesh.position);
  84963. this._debugMesh.color = this.color;
  84964. };
  84965. SkeletonViewer.prototype.dispose = function () {
  84966. if (this._debugMesh) {
  84967. this.isEnabled = false;
  84968. this._debugMesh.dispose();
  84969. this._debugMesh = null;
  84970. }
  84971. };
  84972. return SkeletonViewer;
  84973. }());
  84974. Debug.SkeletonViewer = SkeletonViewer;
  84975. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  84976. })(BABYLON || (BABYLON = {}));
  84977. //# sourceMappingURL=babylon.skeletonViewer.js.map
  84978. /**
  84979. * Module Debug contains the (visual) components to debug a scene correctly
  84980. */
  84981. var BABYLON;
  84982. (function (BABYLON) {
  84983. var Debug;
  84984. (function (Debug) {
  84985. /**
  84986. * The Axes viewer will show 3 axes in a specific point in space
  84987. */
  84988. var AxesViewer = /** @class */ (function () {
  84989. function AxesViewer(scene, scaleLines) {
  84990. if (scaleLines === void 0) { scaleLines = 1; }
  84991. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84992. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84993. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84994. this.scaleLines = 1;
  84995. this.scaleLines = scaleLines;
  84996. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  84997. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  84998. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  84999. this._xmesh.renderingGroupId = 2;
  85000. this._ymesh.renderingGroupId = 2;
  85001. this._zmesh.renderingGroupId = 2;
  85002. this._xmesh.material.checkReadyOnlyOnce = true;
  85003. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  85004. this._ymesh.material.checkReadyOnlyOnce = true;
  85005. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  85006. this._zmesh.material.checkReadyOnlyOnce = true;
  85007. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  85008. this.scene = scene;
  85009. }
  85010. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  85011. var scaleLines = this.scaleLines;
  85012. if (this._xmesh) {
  85013. this._xmesh.position.copyFrom(position);
  85014. }
  85015. if (this._ymesh) {
  85016. this._ymesh.position.copyFrom(position);
  85017. }
  85018. if (this._zmesh) {
  85019. this._zmesh.position.copyFrom(position);
  85020. }
  85021. var point2 = this._xline[1];
  85022. point2.x = xaxis.x * scaleLines;
  85023. point2.y = xaxis.y * scaleLines;
  85024. point2.z = xaxis.z * scaleLines;
  85025. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  85026. point2 = this._yline[1];
  85027. point2.x = yaxis.x * scaleLines;
  85028. point2.y = yaxis.y * scaleLines;
  85029. point2.z = yaxis.z * scaleLines;
  85030. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  85031. point2 = this._zline[1];
  85032. point2.x = zaxis.x * scaleLines;
  85033. point2.y = zaxis.y * scaleLines;
  85034. point2.z = zaxis.z * scaleLines;
  85035. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  85036. };
  85037. AxesViewer.prototype.dispose = function () {
  85038. if (this._xmesh) {
  85039. this._xmesh.dispose();
  85040. }
  85041. if (this._ymesh) {
  85042. this._ymesh.dispose();
  85043. }
  85044. if (this._zmesh) {
  85045. this._zmesh.dispose();
  85046. }
  85047. this._xmesh = null;
  85048. this._ymesh = null;
  85049. this._zmesh = null;
  85050. this.scene = null;
  85051. };
  85052. return AxesViewer;
  85053. }());
  85054. Debug.AxesViewer = AxesViewer;
  85055. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  85056. })(BABYLON || (BABYLON = {}));
  85057. //# sourceMappingURL=babylon.axesViewer.js.map
  85058. var BABYLON;
  85059. (function (BABYLON) {
  85060. var Debug;
  85061. (function (Debug) {
  85062. /**
  85063. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  85064. */
  85065. var BoneAxesViewer = /** @class */ (function (_super) {
  85066. __extends(BoneAxesViewer, _super);
  85067. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  85068. if (scaleLines === void 0) { scaleLines = 1; }
  85069. var _this = _super.call(this, scene, scaleLines) || this;
  85070. _this.pos = BABYLON.Vector3.Zero();
  85071. _this.xaxis = BABYLON.Vector3.Zero();
  85072. _this.yaxis = BABYLON.Vector3.Zero();
  85073. _this.zaxis = BABYLON.Vector3.Zero();
  85074. _this.mesh = mesh;
  85075. _this.bone = bone;
  85076. return _this;
  85077. }
  85078. BoneAxesViewer.prototype.update = function () {
  85079. if (!this.mesh || !this.bone) {
  85080. return;
  85081. }
  85082. var bone = this.bone;
  85083. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  85084. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  85085. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  85086. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  85087. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  85088. };
  85089. BoneAxesViewer.prototype.dispose = function () {
  85090. if (this.mesh) {
  85091. this.mesh = null;
  85092. this.bone = null;
  85093. _super.prototype.dispose.call(this);
  85094. }
  85095. };
  85096. return BoneAxesViewer;
  85097. }(Debug.AxesViewer));
  85098. Debug.BoneAxesViewer = BoneAxesViewer;
  85099. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  85100. })(BABYLON || (BABYLON = {}));
  85101. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  85102. var BABYLON;
  85103. (function (BABYLON) {
  85104. var RayHelper = /** @class */ (function () {
  85105. function RayHelper(ray) {
  85106. this.ray = ray;
  85107. }
  85108. RayHelper.CreateAndShow = function (ray, scene, color) {
  85109. var helper = new RayHelper(ray);
  85110. helper.show(scene, color);
  85111. return helper;
  85112. };
  85113. RayHelper.prototype.show = function (scene, color) {
  85114. if (!this._renderFunction && this.ray) {
  85115. var ray = this.ray;
  85116. this._renderFunction = this._render.bind(this);
  85117. this._scene = scene;
  85118. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  85119. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  85120. if (this._renderFunction) {
  85121. this._scene.registerBeforeRender(this._renderFunction);
  85122. }
  85123. }
  85124. if (color && this._renderLine) {
  85125. this._renderLine.color.copyFrom(color);
  85126. }
  85127. };
  85128. RayHelper.prototype.hide = function () {
  85129. if (this._renderFunction && this._scene) {
  85130. this._scene.unregisterBeforeRender(this._renderFunction);
  85131. this._scene = null;
  85132. this._renderFunction = null;
  85133. if (this._renderLine) {
  85134. this._renderLine.dispose();
  85135. this._renderLine = null;
  85136. }
  85137. this._renderPoints = [];
  85138. }
  85139. };
  85140. RayHelper.prototype._render = function () {
  85141. var ray = this.ray;
  85142. if (!ray) {
  85143. return;
  85144. }
  85145. var point = this._renderPoints[1];
  85146. var len = Math.min(ray.length, 1000000);
  85147. point.copyFrom(ray.direction);
  85148. point.scaleInPlace(len);
  85149. point.addInPlace(ray.origin);
  85150. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  85151. };
  85152. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  85153. this._attachedToMesh = mesh;
  85154. var ray = this.ray;
  85155. if (!ray) {
  85156. return;
  85157. }
  85158. if (!ray.direction) {
  85159. ray.direction = BABYLON.Vector3.Zero();
  85160. }
  85161. if (!ray.origin) {
  85162. ray.origin = BABYLON.Vector3.Zero();
  85163. }
  85164. if (length) {
  85165. ray.length = length;
  85166. }
  85167. if (!meshSpaceOrigin) {
  85168. meshSpaceOrigin = BABYLON.Vector3.Zero();
  85169. }
  85170. if (!meshSpaceDirection) {
  85171. // -1 so that this will work with Mesh.lookAt
  85172. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  85173. }
  85174. if (!this._meshSpaceDirection) {
  85175. this._meshSpaceDirection = meshSpaceDirection.clone();
  85176. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  85177. }
  85178. else {
  85179. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  85180. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  85181. }
  85182. if (!this._updateToMeshFunction) {
  85183. this._updateToMeshFunction = this._updateToMesh.bind(this);
  85184. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  85185. }
  85186. this._updateToMesh();
  85187. };
  85188. RayHelper.prototype.detachFromMesh = function () {
  85189. if (this._attachedToMesh) {
  85190. if (this._updateToMeshFunction) {
  85191. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  85192. }
  85193. this._attachedToMesh = null;
  85194. this._updateToMeshFunction = null;
  85195. }
  85196. };
  85197. RayHelper.prototype._updateToMesh = function () {
  85198. var ray = this.ray;
  85199. if (!this._attachedToMesh || !ray) {
  85200. return;
  85201. }
  85202. if (this._attachedToMesh._isDisposed) {
  85203. this.detachFromMesh();
  85204. return;
  85205. }
  85206. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  85207. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  85208. };
  85209. RayHelper.prototype.dispose = function () {
  85210. this.hide();
  85211. this.detachFromMesh();
  85212. this.ray = null;
  85213. };
  85214. return RayHelper;
  85215. }());
  85216. BABYLON.RayHelper = RayHelper;
  85217. })(BABYLON || (BABYLON = {}));
  85218. //# sourceMappingURL=babylon.rayHelper.js.map
  85219. var BABYLON;
  85220. (function (BABYLON) {
  85221. // load the inspector using require, if not present in the global namespace.
  85222. var DebugLayer = /** @class */ (function () {
  85223. function DebugLayer(scene) {
  85224. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  85225. this._scene = scene;
  85226. // load inspector using require, if it doesn't exist on the global namespace.
  85227. }
  85228. /** Creates the inspector window. */
  85229. DebugLayer.prototype._createInspector = function (config) {
  85230. if (config === void 0) { config = {}; }
  85231. var popup = config.popup || false;
  85232. var initialTab = config.initialTab || 0;
  85233. var parentElement = config.parentElement || null;
  85234. if (!this._inspector) {
  85235. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  85236. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  85237. } // else nothing to do,; instance is already existing
  85238. };
  85239. DebugLayer.prototype.isVisible = function () {
  85240. if (!this._inspector) {
  85241. return false;
  85242. }
  85243. return true;
  85244. };
  85245. DebugLayer.prototype.hide = function () {
  85246. if (this._inspector) {
  85247. try {
  85248. this._inspector.dispose();
  85249. }
  85250. catch (e) {
  85251. // If the inspector has been removed directly from the inspector tool
  85252. }
  85253. this._inspector = null;
  85254. }
  85255. };
  85256. DebugLayer.prototype.show = function (config) {
  85257. if (config === void 0) { config = {}; }
  85258. if (typeof this.BJSINSPECTOR == 'undefined') {
  85259. // Load inspector and add it to the DOM
  85260. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  85261. }
  85262. else {
  85263. // Otherwise creates the inspector
  85264. this._createInspector(config);
  85265. }
  85266. };
  85267. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  85268. return DebugLayer;
  85269. }());
  85270. BABYLON.DebugLayer = DebugLayer;
  85271. })(BABYLON || (BABYLON = {}));
  85272. //# sourceMappingURL=babylon.debugLayer.js.map
  85273. var BABYLON;
  85274. (function (BABYLON) {
  85275. var Debug;
  85276. (function (Debug) {
  85277. /**
  85278. * Used to show the physics impostor around the specific mesh.
  85279. */
  85280. var PhysicsViewer = /** @class */ (function () {
  85281. function PhysicsViewer(scene) {
  85282. this._impostors = [];
  85283. this._meshes = [];
  85284. this._numMeshes = 0;
  85285. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  85286. var physicEngine = this._scene.getPhysicsEngine();
  85287. if (physicEngine) {
  85288. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  85289. }
  85290. }
  85291. PhysicsViewer.prototype._updateDebugMeshes = function () {
  85292. var plugin = this._physicsEnginePlugin;
  85293. for (var i = 0; i < this._numMeshes; i++) {
  85294. var impostor = this._impostors[i];
  85295. if (!impostor) {
  85296. continue;
  85297. }
  85298. if (impostor.isDisposed) {
  85299. this.hideImpostor(this._impostors[i--]);
  85300. }
  85301. else {
  85302. var mesh = this._meshes[i];
  85303. if (mesh && plugin) {
  85304. plugin.syncMeshWithImpostor(mesh, impostor);
  85305. }
  85306. }
  85307. }
  85308. };
  85309. PhysicsViewer.prototype.showImpostor = function (impostor) {
  85310. if (!this._scene) {
  85311. return;
  85312. }
  85313. for (var i = 0; i < this._numMeshes; i++) {
  85314. if (this._impostors[i] == impostor) {
  85315. return;
  85316. }
  85317. }
  85318. var debugMesh = this._getDebugMesh(impostor, this._scene);
  85319. if (debugMesh) {
  85320. this._impostors[this._numMeshes] = impostor;
  85321. this._meshes[this._numMeshes] = debugMesh;
  85322. if (this._numMeshes === 0) {
  85323. this._renderFunction = this._updateDebugMeshes.bind(this);
  85324. this._scene.registerBeforeRender(this._renderFunction);
  85325. }
  85326. this._numMeshes++;
  85327. }
  85328. };
  85329. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  85330. if (!impostor || !this._scene) {
  85331. return;
  85332. }
  85333. var removed = false;
  85334. for (var i = 0; i < this._numMeshes; i++) {
  85335. if (this._impostors[i] == impostor) {
  85336. var mesh = this._meshes[i];
  85337. if (!mesh) {
  85338. continue;
  85339. }
  85340. this._scene.removeMesh(mesh);
  85341. mesh.dispose();
  85342. this._numMeshes--;
  85343. if (this._numMeshes > 0) {
  85344. this._meshes[i] = this._meshes[this._numMeshes];
  85345. this._impostors[i] = this._impostors[this._numMeshes];
  85346. this._meshes[this._numMeshes] = null;
  85347. this._impostors[this._numMeshes] = null;
  85348. }
  85349. else {
  85350. this._meshes[0] = null;
  85351. this._impostors[0] = null;
  85352. }
  85353. removed = true;
  85354. break;
  85355. }
  85356. }
  85357. if (removed && this._numMeshes === 0) {
  85358. this._scene.unregisterBeforeRender(this._renderFunction);
  85359. }
  85360. };
  85361. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  85362. if (!this._debugMaterial) {
  85363. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  85364. this._debugMaterial.wireframe = true;
  85365. }
  85366. return this._debugMaterial;
  85367. };
  85368. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  85369. if (!this._debugBoxMesh) {
  85370. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  85371. this._debugBoxMesh.renderingGroupId = 1;
  85372. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  85373. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  85374. scene.removeMesh(this._debugBoxMesh);
  85375. }
  85376. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  85377. };
  85378. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  85379. if (!this._debugSphereMesh) {
  85380. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  85381. this._debugSphereMesh.renderingGroupId = 1;
  85382. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  85383. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  85384. scene.removeMesh(this._debugSphereMesh);
  85385. }
  85386. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  85387. };
  85388. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  85389. var mesh = null;
  85390. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  85391. mesh = this._getDebugBoxMesh(scene);
  85392. impostor.getBoxSizeToRef(mesh.scaling);
  85393. }
  85394. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  85395. mesh = this._getDebugSphereMesh(scene);
  85396. var radius = impostor.getRadius();
  85397. mesh.scaling.x = radius * 2;
  85398. mesh.scaling.y = radius * 2;
  85399. mesh.scaling.z = radius * 2;
  85400. }
  85401. return mesh;
  85402. };
  85403. PhysicsViewer.prototype.dispose = function () {
  85404. for (var i = 0; i < this._numMeshes; i++) {
  85405. this.hideImpostor(this._impostors[i]);
  85406. }
  85407. if (this._debugBoxMesh) {
  85408. this._debugBoxMesh.dispose();
  85409. }
  85410. if (this._debugSphereMesh) {
  85411. this._debugSphereMesh.dispose();
  85412. }
  85413. if (this._debugMaterial) {
  85414. this._debugMaterial.dispose();
  85415. }
  85416. this._impostors.length = 0;
  85417. this._scene = null;
  85418. this._physicsEnginePlugin = null;
  85419. };
  85420. return PhysicsViewer;
  85421. }());
  85422. Debug.PhysicsViewer = PhysicsViewer;
  85423. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  85424. })(BABYLON || (BABYLON = {}));
  85425. //# sourceMappingURL=babylon.physicsViewer.js.map
  85426. var BABYLON;
  85427. (function (BABYLON) {
  85428. var BoundingBoxRenderer = /** @class */ (function () {
  85429. function BoundingBoxRenderer(scene) {
  85430. this.frontColor = new BABYLON.Color3(1, 1, 1);
  85431. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  85432. this.showBackLines = true;
  85433. this.renderList = new BABYLON.SmartArray(32);
  85434. this._vertexBuffers = {};
  85435. this._scene = scene;
  85436. }
  85437. BoundingBoxRenderer.prototype._prepareRessources = function () {
  85438. if (this._colorShader) {
  85439. return;
  85440. }
  85441. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  85442. attributes: [BABYLON.VertexBuffer.PositionKind],
  85443. uniforms: ["world", "viewProjection", "color"]
  85444. });
  85445. var engine = this._scene.getEngine();
  85446. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  85447. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  85448. this._createIndexBuffer();
  85449. };
  85450. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  85451. var engine = this._scene.getEngine();
  85452. 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]);
  85453. };
  85454. BoundingBoxRenderer.prototype._rebuild = function () {
  85455. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  85456. if (vb) {
  85457. vb._rebuild();
  85458. }
  85459. this._createIndexBuffer();
  85460. };
  85461. BoundingBoxRenderer.prototype.reset = function () {
  85462. this.renderList.reset();
  85463. };
  85464. BoundingBoxRenderer.prototype.render = function () {
  85465. if (this.renderList.length === 0) {
  85466. return;
  85467. }
  85468. this._prepareRessources();
  85469. if (!this._colorShader.isReady()) {
  85470. return;
  85471. }
  85472. var engine = this._scene.getEngine();
  85473. engine.setDepthWrite(false);
  85474. this._colorShader._preBind();
  85475. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  85476. var boundingBox = this.renderList.data[boundingBoxIndex];
  85477. var min = boundingBox.minimum;
  85478. var max = boundingBox.maximum;
  85479. var diff = max.subtract(min);
  85480. var median = min.add(diff.scale(0.5));
  85481. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  85482. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  85483. .multiply(boundingBox.getWorldMatrix());
  85484. // VBOs
  85485. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  85486. if (this.showBackLines) {
  85487. // Back
  85488. engine.setDepthFunctionToGreaterOrEqual();
  85489. this._scene.resetCachedMaterial();
  85490. this._colorShader.setColor4("color", this.backColor.toColor4());
  85491. this._colorShader.bind(worldMatrix);
  85492. // Draw order
  85493. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  85494. }
  85495. // Front
  85496. engine.setDepthFunctionToLess();
  85497. this._scene.resetCachedMaterial();
  85498. this._colorShader.setColor4("color", this.frontColor.toColor4());
  85499. this._colorShader.bind(worldMatrix);
  85500. // Draw order
  85501. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  85502. }
  85503. this._colorShader.unbind();
  85504. engine.setDepthFunctionToLessOrEqual();
  85505. engine.setDepthWrite(true);
  85506. };
  85507. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  85508. this._prepareRessources();
  85509. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  85510. return;
  85511. }
  85512. var engine = this._scene.getEngine();
  85513. engine.setDepthWrite(false);
  85514. engine.setColorWrite(false);
  85515. this._colorShader._preBind();
  85516. var boundingBox = mesh._boundingInfo.boundingBox;
  85517. var min = boundingBox.minimum;
  85518. var max = boundingBox.maximum;
  85519. var diff = max.subtract(min);
  85520. var median = min.add(diff.scale(0.5));
  85521. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  85522. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  85523. .multiply(boundingBox.getWorldMatrix());
  85524. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  85525. engine.setDepthFunctionToLess();
  85526. this._scene.resetCachedMaterial();
  85527. this._colorShader.bind(worldMatrix);
  85528. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  85529. this._colorShader.unbind();
  85530. engine.setDepthFunctionToLessOrEqual();
  85531. engine.setDepthWrite(true);
  85532. engine.setColorWrite(true);
  85533. };
  85534. BoundingBoxRenderer.prototype.dispose = function () {
  85535. if (!this._colorShader) {
  85536. return;
  85537. }
  85538. this.renderList.dispose();
  85539. this._colorShader.dispose();
  85540. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  85541. if (buffer) {
  85542. buffer.dispose();
  85543. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  85544. }
  85545. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  85546. };
  85547. return BoundingBoxRenderer;
  85548. }());
  85549. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  85550. })(BABYLON || (BABYLON = {}));
  85551. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  85552. var BABYLON;
  85553. (function (BABYLON) {
  85554. /**
  85555. * Defines a target to use with MorphTargetManager
  85556. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  85557. */
  85558. var MorphTarget = /** @class */ (function () {
  85559. /**
  85560. * Creates a new MorphTarget
  85561. * @param name defines the name of the target
  85562. * @param influence defines the influence to use
  85563. */
  85564. function MorphTarget(
  85565. /** defines the name of the target */
  85566. name, influence, scene) {
  85567. if (influence === void 0) { influence = 0; }
  85568. if (scene === void 0) { scene = null; }
  85569. this.name = name;
  85570. /**
  85571. * Gets or sets the list of animations
  85572. */
  85573. this.animations = new Array();
  85574. this._positions = null;
  85575. this._normals = null;
  85576. this._tangents = null;
  85577. /**
  85578. * Observable raised when the influence changes
  85579. */
  85580. this.onInfluenceChanged = new BABYLON.Observable();
  85581. this._animationPropertiesOverride = null;
  85582. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  85583. this.influence = influence;
  85584. }
  85585. Object.defineProperty(MorphTarget.prototype, "influence", {
  85586. /**
  85587. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  85588. */
  85589. get: function () {
  85590. return this._influence;
  85591. },
  85592. set: function (influence) {
  85593. if (this._influence === influence) {
  85594. return;
  85595. }
  85596. var previous = this._influence;
  85597. this._influence = influence;
  85598. if (this.onInfluenceChanged.hasObservers) {
  85599. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  85600. }
  85601. },
  85602. enumerable: true,
  85603. configurable: true
  85604. });
  85605. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  85606. /**
  85607. * Gets or sets the animation properties override
  85608. */
  85609. get: function () {
  85610. if (!this._animationPropertiesOverride && this._scene) {
  85611. return this._scene.animationPropertiesOverride;
  85612. }
  85613. return this._animationPropertiesOverride;
  85614. },
  85615. set: function (value) {
  85616. this._animationPropertiesOverride = value;
  85617. },
  85618. enumerable: true,
  85619. configurable: true
  85620. });
  85621. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  85622. /**
  85623. * Gets a boolean defining if the target contains position data
  85624. */
  85625. get: function () {
  85626. return !!this._positions;
  85627. },
  85628. enumerable: true,
  85629. configurable: true
  85630. });
  85631. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  85632. /**
  85633. * Gets a boolean defining if the target contains normal data
  85634. */
  85635. get: function () {
  85636. return !!this._normals;
  85637. },
  85638. enumerable: true,
  85639. configurable: true
  85640. });
  85641. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  85642. /**
  85643. * Gets a boolean defining if the target contains tangent data
  85644. */
  85645. get: function () {
  85646. return !!this._tangents;
  85647. },
  85648. enumerable: true,
  85649. configurable: true
  85650. });
  85651. /**
  85652. * Affects position data to this target
  85653. * @param data defines the position data to use
  85654. */
  85655. MorphTarget.prototype.setPositions = function (data) {
  85656. this._positions = data;
  85657. };
  85658. /**
  85659. * Gets the position data stored in this target
  85660. * @returns a FloatArray containing the position data (or null if not present)
  85661. */
  85662. MorphTarget.prototype.getPositions = function () {
  85663. return this._positions;
  85664. };
  85665. /**
  85666. * Affects normal data to this target
  85667. * @param data defines the normal data to use
  85668. */
  85669. MorphTarget.prototype.setNormals = function (data) {
  85670. this._normals = data;
  85671. };
  85672. /**
  85673. * Gets the normal data stored in this target
  85674. * @returns a FloatArray containing the normal data (or null if not present)
  85675. */
  85676. MorphTarget.prototype.getNormals = function () {
  85677. return this._normals;
  85678. };
  85679. /**
  85680. * Affects tangent data to this target
  85681. * @param data defines the tangent data to use
  85682. */
  85683. MorphTarget.prototype.setTangents = function (data) {
  85684. this._tangents = data;
  85685. };
  85686. /**
  85687. * Gets the tangent data stored in this target
  85688. * @returns a FloatArray containing the tangent data (or null if not present)
  85689. */
  85690. MorphTarget.prototype.getTangents = function () {
  85691. return this._tangents;
  85692. };
  85693. /**
  85694. * Serializes the current target into a Serialization object
  85695. * @returns the serialized object
  85696. */
  85697. MorphTarget.prototype.serialize = function () {
  85698. var serializationObject = {};
  85699. serializationObject.name = this.name;
  85700. serializationObject.influence = this.influence;
  85701. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  85702. if (this.hasNormals) {
  85703. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  85704. }
  85705. if (this.hasTangents) {
  85706. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  85707. }
  85708. // Animations
  85709. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  85710. return serializationObject;
  85711. };
  85712. // Statics
  85713. /**
  85714. * Creates a new target from serialized data
  85715. * @param serializationObject defines the serialized data to use
  85716. * @returns a new MorphTarget
  85717. */
  85718. MorphTarget.Parse = function (serializationObject) {
  85719. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  85720. result.setPositions(serializationObject.positions);
  85721. if (serializationObject.normals) {
  85722. result.setNormals(serializationObject.normals);
  85723. }
  85724. if (serializationObject.tangents) {
  85725. result.setTangents(serializationObject.tangents);
  85726. }
  85727. // Animations
  85728. if (serializationObject.animations) {
  85729. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  85730. var parsedAnimation = serializationObject.animations[animationIndex];
  85731. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  85732. }
  85733. }
  85734. return result;
  85735. };
  85736. /**
  85737. * Creates a MorphTarget from mesh data
  85738. * @param mesh defines the source mesh
  85739. * @param name defines the name to use for the new target
  85740. * @param influence defines the influence to attach to the target
  85741. * @returns a new MorphTarget
  85742. */
  85743. MorphTarget.FromMesh = function (mesh, name, influence) {
  85744. if (!name) {
  85745. name = mesh.name;
  85746. }
  85747. var result = new MorphTarget(name, influence, mesh.getScene());
  85748. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  85749. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  85750. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  85751. }
  85752. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  85753. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  85754. }
  85755. return result;
  85756. };
  85757. return MorphTarget;
  85758. }());
  85759. BABYLON.MorphTarget = MorphTarget;
  85760. })(BABYLON || (BABYLON = {}));
  85761. //# sourceMappingURL=babylon.morphTarget.js.map
  85762. var BABYLON;
  85763. (function (BABYLON) {
  85764. /**
  85765. * This class is used to deform meshes using morphing between different targets
  85766. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  85767. */
  85768. var MorphTargetManager = /** @class */ (function () {
  85769. /**
  85770. * Creates a new MorphTargetManager
  85771. * @param scene defines the current scene
  85772. */
  85773. function MorphTargetManager(scene) {
  85774. if (scene === void 0) { scene = null; }
  85775. this._targets = new Array();
  85776. this._targetObservable = new Array();
  85777. this._activeTargets = new BABYLON.SmartArray(16);
  85778. this._supportsNormals = false;
  85779. this._supportsTangents = false;
  85780. this._vertexCount = 0;
  85781. this._uniqueId = 0;
  85782. this._tempInfluences = new Array();
  85783. if (!scene) {
  85784. scene = BABYLON.Engine.LastCreatedScene;
  85785. }
  85786. this._scene = scene;
  85787. if (this._scene) {
  85788. this._scene.morphTargetManagers.push(this);
  85789. this._uniqueId = this._scene.getUniqueId();
  85790. }
  85791. }
  85792. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  85793. /**
  85794. * Gets the unique ID of this manager
  85795. */
  85796. get: function () {
  85797. return this._uniqueId;
  85798. },
  85799. enumerable: true,
  85800. configurable: true
  85801. });
  85802. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  85803. /**
  85804. * Gets the number of vertices handled by this manager
  85805. */
  85806. get: function () {
  85807. return this._vertexCount;
  85808. },
  85809. enumerable: true,
  85810. configurable: true
  85811. });
  85812. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  85813. /**
  85814. * Gets a boolean indicating if this manager supports morphing of normals
  85815. */
  85816. get: function () {
  85817. return this._supportsNormals;
  85818. },
  85819. enumerable: true,
  85820. configurable: true
  85821. });
  85822. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  85823. /**
  85824. * Gets a boolean indicating if this manager supports morphing of tangents
  85825. */
  85826. get: function () {
  85827. return this._supportsTangents;
  85828. },
  85829. enumerable: true,
  85830. configurable: true
  85831. });
  85832. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  85833. /**
  85834. * Gets the number of targets stored in this manager
  85835. */
  85836. get: function () {
  85837. return this._targets.length;
  85838. },
  85839. enumerable: true,
  85840. configurable: true
  85841. });
  85842. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  85843. /**
  85844. * Gets the number of influencers (ie. the number of targets with influences > 0)
  85845. */
  85846. get: function () {
  85847. return this._activeTargets.length;
  85848. },
  85849. enumerable: true,
  85850. configurable: true
  85851. });
  85852. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  85853. /**
  85854. * Gets the list of influences (one per target)
  85855. */
  85856. get: function () {
  85857. return this._influences;
  85858. },
  85859. enumerable: true,
  85860. configurable: true
  85861. });
  85862. /**
  85863. * Gets the active target at specified index. An active target is a target with an influence > 0
  85864. * @param index defines the index to check
  85865. * @returns the requested target
  85866. */
  85867. MorphTargetManager.prototype.getActiveTarget = function (index) {
  85868. return this._activeTargets.data[index];
  85869. };
  85870. /**
  85871. * Gets the target at specified index
  85872. * @param index defines the index to check
  85873. * @returns the requested target
  85874. */
  85875. MorphTargetManager.prototype.getTarget = function (index) {
  85876. return this._targets[index];
  85877. };
  85878. /**
  85879. * Add a new target to this manager
  85880. * @param target defines the target to add
  85881. */
  85882. MorphTargetManager.prototype.addTarget = function (target) {
  85883. var _this = this;
  85884. this._targets.push(target);
  85885. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  85886. _this._syncActiveTargets(needUpdate);
  85887. }));
  85888. this._syncActiveTargets(true);
  85889. };
  85890. /**
  85891. * Removes a target from the manager
  85892. * @param target defines the target to remove
  85893. */
  85894. MorphTargetManager.prototype.removeTarget = function (target) {
  85895. var index = this._targets.indexOf(target);
  85896. if (index >= 0) {
  85897. this._targets.splice(index, 1);
  85898. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  85899. this._syncActiveTargets(true);
  85900. }
  85901. };
  85902. /**
  85903. * Serializes the current manager into a Serialization object
  85904. * @returns the serialized object
  85905. */
  85906. MorphTargetManager.prototype.serialize = function () {
  85907. var serializationObject = {};
  85908. serializationObject.id = this.uniqueId;
  85909. serializationObject.targets = [];
  85910. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  85911. var target = _a[_i];
  85912. serializationObject.targets.push(target.serialize());
  85913. }
  85914. return serializationObject;
  85915. };
  85916. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  85917. var influenceCount = 0;
  85918. this._activeTargets.reset();
  85919. this._supportsNormals = true;
  85920. this._supportsTangents = true;
  85921. this._vertexCount = 0;
  85922. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  85923. var target = _a[_i];
  85924. this._activeTargets.push(target);
  85925. this._tempInfluences[influenceCount++] = target.influence;
  85926. var positions = target.getPositions();
  85927. if (positions) {
  85928. this._supportsNormals = this._supportsNormals && target.hasNormals;
  85929. this._supportsTangents = this._supportsTangents && target.hasTangents;
  85930. var vertexCount = positions.length / 3;
  85931. if (this._vertexCount === 0) {
  85932. this._vertexCount = vertexCount;
  85933. }
  85934. else if (this._vertexCount !== vertexCount) {
  85935. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  85936. return;
  85937. }
  85938. }
  85939. }
  85940. if (!this._influences || this._influences.length !== influenceCount) {
  85941. this._influences = new Float32Array(influenceCount);
  85942. }
  85943. for (var index = 0; index < influenceCount; index++) {
  85944. this._influences[index] = this._tempInfluences[index];
  85945. }
  85946. if (needUpdate) {
  85947. this.synchronize();
  85948. }
  85949. };
  85950. /**
  85951. * Syncrhonize the targets with all the meshes using this morph target manager
  85952. */
  85953. MorphTargetManager.prototype.synchronize = function () {
  85954. if (!this._scene) {
  85955. return;
  85956. }
  85957. // Flag meshes as dirty to resync with the active targets
  85958. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  85959. var mesh = _a[_i];
  85960. if (mesh.morphTargetManager === this) {
  85961. mesh._syncGeometryWithMorphTargetManager();
  85962. }
  85963. }
  85964. };
  85965. // Statics
  85966. /**
  85967. * Creates a new MorphTargetManager from serialized data
  85968. * @param serializationObject defines the serialized data
  85969. * @param scene defines the hosting scene
  85970. * @returns the new MorphTargetManager
  85971. */
  85972. MorphTargetManager.Parse = function (serializationObject, scene) {
  85973. var result = new MorphTargetManager(scene);
  85974. result._uniqueId = serializationObject.id;
  85975. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  85976. var targetData = _a[_i];
  85977. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  85978. }
  85979. return result;
  85980. };
  85981. return MorphTargetManager;
  85982. }());
  85983. BABYLON.MorphTargetManager = MorphTargetManager;
  85984. })(BABYLON || (BABYLON = {}));
  85985. //# sourceMappingURL=babylon.morphTargetManager.js.map
  85986. var BABYLON;
  85987. (function (BABYLON) {
  85988. var Octree = /** @class */ (function () {
  85989. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  85990. if (maxDepth === void 0) { maxDepth = 2; }
  85991. this.maxDepth = maxDepth;
  85992. this.dynamicContent = new Array();
  85993. this._maxBlockCapacity = maxBlockCapacity || 64;
  85994. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  85995. this._creationFunc = creationFunc;
  85996. }
  85997. // Methods
  85998. Octree.prototype.update = function (worldMin, worldMax, entries) {
  85999. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  86000. };
  86001. Octree.prototype.addMesh = function (entry) {
  86002. for (var index = 0; index < this.blocks.length; index++) {
  86003. var block = this.blocks[index];
  86004. block.addEntry(entry);
  86005. }
  86006. };
  86007. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  86008. this._selectionContent.reset();
  86009. for (var index = 0; index < this.blocks.length; index++) {
  86010. var block = this.blocks[index];
  86011. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  86012. }
  86013. if (allowDuplicate) {
  86014. this._selectionContent.concat(this.dynamicContent);
  86015. }
  86016. else {
  86017. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  86018. }
  86019. return this._selectionContent;
  86020. };
  86021. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  86022. this._selectionContent.reset();
  86023. for (var index = 0; index < this.blocks.length; index++) {
  86024. var block = this.blocks[index];
  86025. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  86026. }
  86027. if (allowDuplicate) {
  86028. this._selectionContent.concat(this.dynamicContent);
  86029. }
  86030. else {
  86031. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  86032. }
  86033. return this._selectionContent;
  86034. };
  86035. Octree.prototype.intersectsRay = function (ray) {
  86036. this._selectionContent.reset();
  86037. for (var index = 0; index < this.blocks.length; index++) {
  86038. var block = this.blocks[index];
  86039. block.intersectsRay(ray, this._selectionContent);
  86040. }
  86041. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  86042. return this._selectionContent;
  86043. };
  86044. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  86045. target.blocks = new Array();
  86046. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  86047. // Segmenting space
  86048. for (var x = 0; x < 2; x++) {
  86049. for (var y = 0; y < 2; y++) {
  86050. for (var z = 0; z < 2; z++) {
  86051. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  86052. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  86053. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  86054. block.addEntries(entries);
  86055. target.blocks.push(block);
  86056. }
  86057. }
  86058. }
  86059. };
  86060. Octree.CreationFuncForMeshes = function (entry, block) {
  86061. var boundingInfo = entry.getBoundingInfo();
  86062. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  86063. block.entries.push(entry);
  86064. }
  86065. };
  86066. Octree.CreationFuncForSubMeshes = function (entry, block) {
  86067. var boundingInfo = entry.getBoundingInfo();
  86068. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  86069. block.entries.push(entry);
  86070. }
  86071. };
  86072. return Octree;
  86073. }());
  86074. BABYLON.Octree = Octree;
  86075. })(BABYLON || (BABYLON = {}));
  86076. //# sourceMappingURL=babylon.octree.js.map
  86077. var BABYLON;
  86078. (function (BABYLON) {
  86079. var OctreeBlock = /** @class */ (function () {
  86080. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  86081. this.entries = new Array();
  86082. this._boundingVectors = new Array();
  86083. this._capacity = capacity;
  86084. this._depth = depth;
  86085. this._maxDepth = maxDepth;
  86086. this._creationFunc = creationFunc;
  86087. this._minPoint = minPoint;
  86088. this._maxPoint = maxPoint;
  86089. this._boundingVectors.push(minPoint.clone());
  86090. this._boundingVectors.push(maxPoint.clone());
  86091. this._boundingVectors.push(minPoint.clone());
  86092. this._boundingVectors[2].x = maxPoint.x;
  86093. this._boundingVectors.push(minPoint.clone());
  86094. this._boundingVectors[3].y = maxPoint.y;
  86095. this._boundingVectors.push(minPoint.clone());
  86096. this._boundingVectors[4].z = maxPoint.z;
  86097. this._boundingVectors.push(maxPoint.clone());
  86098. this._boundingVectors[5].z = minPoint.z;
  86099. this._boundingVectors.push(maxPoint.clone());
  86100. this._boundingVectors[6].x = minPoint.x;
  86101. this._boundingVectors.push(maxPoint.clone());
  86102. this._boundingVectors[7].y = minPoint.y;
  86103. }
  86104. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  86105. // Property
  86106. get: function () {
  86107. return this._capacity;
  86108. },
  86109. enumerable: true,
  86110. configurable: true
  86111. });
  86112. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  86113. get: function () {
  86114. return this._minPoint;
  86115. },
  86116. enumerable: true,
  86117. configurable: true
  86118. });
  86119. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  86120. get: function () {
  86121. return this._maxPoint;
  86122. },
  86123. enumerable: true,
  86124. configurable: true
  86125. });
  86126. // Methods
  86127. OctreeBlock.prototype.addEntry = function (entry) {
  86128. if (this.blocks) {
  86129. for (var index = 0; index < this.blocks.length; index++) {
  86130. var block = this.blocks[index];
  86131. block.addEntry(entry);
  86132. }
  86133. return;
  86134. }
  86135. this._creationFunc(entry, this);
  86136. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  86137. this.createInnerBlocks();
  86138. }
  86139. };
  86140. OctreeBlock.prototype.addEntries = function (entries) {
  86141. for (var index = 0; index < entries.length; index++) {
  86142. var mesh = entries[index];
  86143. this.addEntry(mesh);
  86144. }
  86145. };
  86146. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  86147. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  86148. if (this.blocks) {
  86149. for (var index = 0; index < this.blocks.length; index++) {
  86150. var block = this.blocks[index];
  86151. block.select(frustumPlanes, selection, allowDuplicate);
  86152. }
  86153. return;
  86154. }
  86155. if (allowDuplicate) {
  86156. selection.concat(this.entries);
  86157. }
  86158. else {
  86159. selection.concatWithNoDuplicate(this.entries);
  86160. }
  86161. }
  86162. };
  86163. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  86164. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  86165. if (this.blocks) {
  86166. for (var index = 0; index < this.blocks.length; index++) {
  86167. var block = this.blocks[index];
  86168. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  86169. }
  86170. return;
  86171. }
  86172. if (allowDuplicate) {
  86173. selection.concat(this.entries);
  86174. }
  86175. else {
  86176. selection.concatWithNoDuplicate(this.entries);
  86177. }
  86178. }
  86179. };
  86180. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  86181. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  86182. if (this.blocks) {
  86183. for (var index = 0; index < this.blocks.length; index++) {
  86184. var block = this.blocks[index];
  86185. block.intersectsRay(ray, selection);
  86186. }
  86187. return;
  86188. }
  86189. selection.concatWithNoDuplicate(this.entries);
  86190. }
  86191. };
  86192. OctreeBlock.prototype.createInnerBlocks = function () {
  86193. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  86194. };
  86195. return OctreeBlock;
  86196. }());
  86197. BABYLON.OctreeBlock = OctreeBlock;
  86198. })(BABYLON || (BABYLON = {}));
  86199. //# sourceMappingURL=babylon.octreeBlock.js.map
  86200. var BABYLON;
  86201. (function (BABYLON) {
  86202. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  86203. __extends(VRDistortionCorrectionPostProcess, _super);
  86204. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  86205. var _this = _super.call(this, name, "vrDistortionCorrection", [
  86206. 'LensCenter',
  86207. 'Scale',
  86208. 'ScaleIn',
  86209. 'HmdWarpParam'
  86210. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  86211. _this._isRightEye = isRightEye;
  86212. _this._distortionFactors = vrMetrics.distortionK;
  86213. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  86214. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  86215. _this.adaptScaleToCurrentViewport = true;
  86216. _this.onSizeChangedObservable.add(function () {
  86217. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  86218. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  86219. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  86220. });
  86221. _this.onApplyObservable.add(function (effect) {
  86222. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  86223. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  86224. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  86225. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  86226. });
  86227. return _this;
  86228. }
  86229. return VRDistortionCorrectionPostProcess;
  86230. }(BABYLON.PostProcess));
  86231. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  86232. })(BABYLON || (BABYLON = {}));
  86233. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  86234. var BABYLON;
  86235. (function (BABYLON) {
  86236. /**
  86237. * Postprocess used to generate anaglyphic rendering
  86238. */
  86239. var AnaglyphPostProcess = /** @class */ (function (_super) {
  86240. __extends(AnaglyphPostProcess, _super);
  86241. /**
  86242. * Creates a new AnaglyphPostProcess
  86243. * @param name defines postprocess name
  86244. * @param options defines creation options or target ratio scale
  86245. * @param rigCameras defines cameras using this postprocess
  86246. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  86247. * @param engine defines hosting engine
  86248. * @param reusable defines if the postprocess will be reused multiple times per frame
  86249. */
  86250. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  86251. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  86252. _this._passedProcess = rigCameras[0]._rigPostProcess;
  86253. _this.onApplyObservable.add(function (effect) {
  86254. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  86255. });
  86256. return _this;
  86257. }
  86258. return AnaglyphPostProcess;
  86259. }(BABYLON.PostProcess));
  86260. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  86261. })(BABYLON || (BABYLON = {}));
  86262. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  86263. var BABYLON;
  86264. (function (BABYLON) {
  86265. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  86266. __extends(StereoscopicInterlacePostProcess, _super);
  86267. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  86268. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  86269. _this._passedProcess = rigCameras[0]._rigPostProcess;
  86270. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  86271. _this.onSizeChangedObservable.add(function () {
  86272. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  86273. });
  86274. _this.onApplyObservable.add(function (effect) {
  86275. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  86276. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  86277. });
  86278. return _this;
  86279. }
  86280. return StereoscopicInterlacePostProcess;
  86281. }(BABYLON.PostProcess));
  86282. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  86283. })(BABYLON || (BABYLON = {}));
  86284. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  86285. var BABYLON;
  86286. (function (BABYLON) {
  86287. /**
  86288. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  86289. * Screen rotation is taken into account.
  86290. */
  86291. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  86292. function FreeCameraDeviceOrientationInput() {
  86293. var _this = this;
  86294. this._screenOrientationAngle = 0;
  86295. this._screenQuaternion = new BABYLON.Quaternion();
  86296. this._alpha = 0;
  86297. this._beta = 0;
  86298. this._gamma = 0;
  86299. this._orientationChanged = function () {
  86300. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  86301. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  86302. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  86303. };
  86304. this._deviceOrientation = function (evt) {
  86305. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  86306. _this._beta = evt.beta !== null ? evt.beta : 0;
  86307. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  86308. };
  86309. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  86310. this._orientationChanged();
  86311. }
  86312. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  86313. get: function () {
  86314. return this._camera;
  86315. },
  86316. set: function (camera) {
  86317. this._camera = camera;
  86318. if (this._camera != null && !this._camera.rotationQuaternion) {
  86319. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  86320. }
  86321. },
  86322. enumerable: true,
  86323. configurable: true
  86324. });
  86325. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  86326. window.addEventListener("orientationchange", this._orientationChanged);
  86327. window.addEventListener("deviceorientation", this._deviceOrientation);
  86328. //In certain cases, the attach control is called AFTER orientation was changed,
  86329. //So this is needed.
  86330. this._orientationChanged();
  86331. };
  86332. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  86333. window.removeEventListener("orientationchange", this._orientationChanged);
  86334. window.removeEventListener("deviceorientation", this._deviceOrientation);
  86335. };
  86336. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  86337. //if no device orientation provided, don't update the rotation.
  86338. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  86339. if (!this._alpha)
  86340. return;
  86341. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  86342. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  86343. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  86344. //Mirror on XY Plane
  86345. this._camera.rotationQuaternion.z *= -1;
  86346. this._camera.rotationQuaternion.w *= -1;
  86347. };
  86348. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  86349. return "FreeCameraDeviceOrientationInput";
  86350. };
  86351. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  86352. return "deviceOrientation";
  86353. };
  86354. return FreeCameraDeviceOrientationInput;
  86355. }());
  86356. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  86357. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  86358. })(BABYLON || (BABYLON = {}));
  86359. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  86360. var BABYLON;
  86361. (function (BABYLON) {
  86362. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  86363. function ArcRotateCameraVRDeviceOrientationInput() {
  86364. this.alphaCorrection = 1;
  86365. this.betaCorrection = 1;
  86366. this.gammaCorrection = 1;
  86367. this._alpha = 0;
  86368. this._gamma = 0;
  86369. this._dirty = false;
  86370. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  86371. }
  86372. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  86373. this.camera.attachControl(element, noPreventDefault);
  86374. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  86375. };
  86376. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  86377. if (evt.alpha !== null) {
  86378. this._alpha = +evt.alpha | 0;
  86379. }
  86380. if (evt.gamma !== null) {
  86381. this._gamma = +evt.gamma | 0;
  86382. }
  86383. this._dirty = true;
  86384. };
  86385. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  86386. if (this._dirty) {
  86387. this._dirty = false;
  86388. if (this._gamma < 0) {
  86389. this._gamma = 180 + this._gamma;
  86390. }
  86391. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  86392. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  86393. }
  86394. };
  86395. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  86396. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  86397. };
  86398. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  86399. return "ArcRotateCameraVRDeviceOrientationInput";
  86400. };
  86401. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  86402. return "VRDeviceOrientation";
  86403. };
  86404. return ArcRotateCameraVRDeviceOrientationInput;
  86405. }());
  86406. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  86407. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  86408. })(BABYLON || (BABYLON = {}));
  86409. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  86410. var BABYLON;
  86411. (function (BABYLON) {
  86412. var VRCameraMetrics = /** @class */ (function () {
  86413. function VRCameraMetrics() {
  86414. this.compensateDistortion = true;
  86415. }
  86416. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  86417. get: function () {
  86418. return this.hResolution / (2 * this.vResolution);
  86419. },
  86420. enumerable: true,
  86421. configurable: true
  86422. });
  86423. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  86424. get: function () {
  86425. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  86426. },
  86427. enumerable: true,
  86428. configurable: true
  86429. });
  86430. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  86431. get: function () {
  86432. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  86433. var h = (4 * meters) / this.hScreenSize;
  86434. return BABYLON.Matrix.Translation(h, 0, 0);
  86435. },
  86436. enumerable: true,
  86437. configurable: true
  86438. });
  86439. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  86440. get: function () {
  86441. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  86442. var h = (4 * meters) / this.hScreenSize;
  86443. return BABYLON.Matrix.Translation(-h, 0, 0);
  86444. },
  86445. enumerable: true,
  86446. configurable: true
  86447. });
  86448. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  86449. get: function () {
  86450. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  86451. },
  86452. enumerable: true,
  86453. configurable: true
  86454. });
  86455. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  86456. get: function () {
  86457. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  86458. },
  86459. enumerable: true,
  86460. configurable: true
  86461. });
  86462. VRCameraMetrics.GetDefault = function () {
  86463. var result = new VRCameraMetrics();
  86464. result.hResolution = 1280;
  86465. result.vResolution = 800;
  86466. result.hScreenSize = 0.149759993;
  86467. result.vScreenSize = 0.0935999975;
  86468. result.vScreenCenter = 0.0467999987;
  86469. result.eyeToScreenDistance = 0.0410000011;
  86470. result.lensSeparationDistance = 0.0635000020;
  86471. result.interpupillaryDistance = 0.0640000030;
  86472. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  86473. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  86474. result.postProcessScaleFactor = 1.714605507808412;
  86475. result.lensCenterOffset = 0.151976421;
  86476. return result;
  86477. };
  86478. return VRCameraMetrics;
  86479. }());
  86480. BABYLON.VRCameraMetrics = VRCameraMetrics;
  86481. })(BABYLON || (BABYLON = {}));
  86482. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  86483. var BABYLON;
  86484. (function (BABYLON) {
  86485. /**
  86486. * This represents a WebVR camera.
  86487. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  86488. * @example http://doc.babylonjs.com/how_to/webvr_camera
  86489. */
  86490. var WebVRFreeCamera = /** @class */ (function (_super) {
  86491. __extends(WebVRFreeCamera, _super);
  86492. /**
  86493. * Instantiates a WebVRFreeCamera.
  86494. * @param name The name of the WebVRFreeCamera
  86495. * @param position The starting anchor position for the camera
  86496. * @param scene The scene the camera belongs to
  86497. * @param webVROptions a set of customizable options for the webVRCamera
  86498. */
  86499. function WebVRFreeCamera(name, position, scene, webVROptions) {
  86500. if (webVROptions === void 0) { webVROptions = {}; }
  86501. var _this = _super.call(this, name, position, scene) || this;
  86502. _this.webVROptions = webVROptions;
  86503. /**
  86504. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  86505. */
  86506. _this._vrDevice = null;
  86507. /**
  86508. * The rawPose of the vrDevice.
  86509. */
  86510. _this.rawPose = null;
  86511. _this._specsVersion = "1.1";
  86512. _this._attached = false;
  86513. _this._descendants = [];
  86514. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  86515. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  86516. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  86517. _this._standingMatrix = null;
  86518. /**
  86519. * Represents device position in babylon space.
  86520. */
  86521. _this.devicePosition = BABYLON.Vector3.Zero();
  86522. /**
  86523. * Represents device rotation in babylon space.
  86524. */
  86525. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  86526. /**
  86527. * The scale of the device to be used when translating from device space to babylon space.
  86528. */
  86529. _this.deviceScaleFactor = 1;
  86530. _this._deviceToWorld = BABYLON.Matrix.Identity();
  86531. _this._worldToDevice = BABYLON.Matrix.Identity();
  86532. /**
  86533. * References to the webVR controllers for the vrDevice.
  86534. */
  86535. _this.controllers = [];
  86536. /**
  86537. * Emits an event when a controller is attached.
  86538. */
  86539. _this.onControllersAttachedObservable = new BABYLON.Observable();
  86540. /**
  86541. * Emits an event when a controller's mesh has been loaded;
  86542. */
  86543. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  86544. /**
  86545. * If the rig cameras be used as parent instead of this camera.
  86546. */
  86547. _this.rigParenting = true;
  86548. _this._defaultHeight = undefined;
  86549. _this._workingVector = BABYLON.Vector3.Zero();
  86550. _this._oneVector = BABYLON.Vector3.One();
  86551. _this._workingMatrix = BABYLON.Matrix.Identity();
  86552. _this._cache.position = BABYLON.Vector3.Zero();
  86553. if (webVROptions.defaultHeight) {
  86554. _this._defaultHeight = webVROptions.defaultHeight;
  86555. _this.position.y = _this._defaultHeight;
  86556. }
  86557. _this.minZ = 0.1;
  86558. //legacy support - the compensation boolean was removed.
  86559. if (arguments.length === 5) {
  86560. _this.webVROptions = arguments[4];
  86561. }
  86562. // default webVR options
  86563. if (_this.webVROptions.trackPosition == undefined) {
  86564. _this.webVROptions.trackPosition = true;
  86565. }
  86566. if (_this.webVROptions.controllerMeshes == undefined) {
  86567. _this.webVROptions.controllerMeshes = true;
  86568. }
  86569. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  86570. _this.webVROptions.defaultLightingOnControllers = true;
  86571. }
  86572. _this.rotationQuaternion = new BABYLON.Quaternion();
  86573. if (_this.webVROptions && _this.webVROptions.positionScale) {
  86574. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  86575. }
  86576. //enable VR
  86577. var engine = _this.getEngine();
  86578. _this._onVREnabled = function (success) { if (success) {
  86579. _this.initControllers();
  86580. } };
  86581. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  86582. engine.initWebVR().add(function (event) {
  86583. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  86584. return;
  86585. }
  86586. _this._vrDevice = event.vrDisplay;
  86587. //reset the rig parameters.
  86588. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  86589. if (_this._attached) {
  86590. _this.getEngine().enableVR();
  86591. }
  86592. });
  86593. if (typeof (VRFrameData) !== "undefined")
  86594. _this._frameData = new VRFrameData();
  86595. /**
  86596. * The idea behind the following lines:
  86597. * objects that have the camera as parent should actually have the rig cameras as a parent.
  86598. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  86599. * the second will not show it correctly.
  86600. *
  86601. * To solve this - each object that has the camera as parent will be added to a protected array.
  86602. * When the rig camera renders, it will take this array and set all of those to be its children.
  86603. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  86604. * Amazing!
  86605. */
  86606. scene.onBeforeCameraRenderObservable.add(function (camera) {
  86607. if (camera.parent === _this && _this.rigParenting) {
  86608. _this._descendants = _this.getDescendants(true, function (n) {
  86609. // don't take the cameras or the controllers!
  86610. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  86611. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  86612. return !isController && !isRigCamera;
  86613. });
  86614. _this._descendants.forEach(function (node) {
  86615. node.parent = camera;
  86616. });
  86617. }
  86618. });
  86619. scene.onAfterCameraRenderObservable.add(function (camera) {
  86620. if (camera.parent === _this && _this.rigParenting) {
  86621. _this._descendants.forEach(function (node) {
  86622. node.parent = _this;
  86623. });
  86624. }
  86625. });
  86626. return _this;
  86627. }
  86628. /**
  86629. * Gets the device distance from the ground in meters.
  86630. * @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.
  86631. */
  86632. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  86633. if (this._standingMatrix) {
  86634. // Add standing matrix offset to get real offset from ground in room
  86635. this._standingMatrix.getTranslationToRef(this._workingVector);
  86636. return this._deviceRoomPosition.y + this._workingVector.y;
  86637. }
  86638. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  86639. return this._defaultHeight || 0;
  86640. };
  86641. /**
  86642. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  86643. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  86644. */
  86645. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  86646. var _this = this;
  86647. if (callback === void 0) { callback = function (bool) { }; }
  86648. // Use standing matrix if available
  86649. this.getEngine().initWebVRAsync().then(function (result) {
  86650. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  86651. callback(false);
  86652. }
  86653. else {
  86654. _this._standingMatrix = new BABYLON.Matrix();
  86655. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  86656. if (!_this.getScene().useRightHandedSystem) {
  86657. [2, 6, 8, 9, 14].forEach(function (num) {
  86658. if (_this._standingMatrix) {
  86659. _this._standingMatrix.m[num] *= -1;
  86660. }
  86661. });
  86662. }
  86663. callback(true);
  86664. }
  86665. });
  86666. };
  86667. /**
  86668. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  86669. * @returns A promise with a boolean set to if the standing matrix is supported.
  86670. */
  86671. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  86672. var _this = this;
  86673. return new Promise(function (res, rej) {
  86674. _this.useStandingMatrix(function (supported) {
  86675. res(supported);
  86676. });
  86677. });
  86678. };
  86679. /**
  86680. * Disposes the camera
  86681. */
  86682. WebVRFreeCamera.prototype.dispose = function () {
  86683. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  86684. _super.prototype.dispose.call(this);
  86685. };
  86686. /**
  86687. * Gets a vrController by name.
  86688. * @param name The name of the controller to retreive
  86689. * @returns the controller matching the name specified or null if not found
  86690. */
  86691. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  86692. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  86693. var gp = _a[_i];
  86694. if (gp.hand === name) {
  86695. return gp;
  86696. }
  86697. }
  86698. return null;
  86699. };
  86700. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  86701. /**
  86702. * The controller corrisponding to the users left hand.
  86703. */
  86704. get: function () {
  86705. if (!this._leftController) {
  86706. this._leftController = this.getControllerByName("left");
  86707. }
  86708. return this._leftController;
  86709. },
  86710. enumerable: true,
  86711. configurable: true
  86712. });
  86713. ;
  86714. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  86715. /**
  86716. * The controller corrisponding to the users right hand.
  86717. */
  86718. get: function () {
  86719. if (!this._rightController) {
  86720. this._rightController = this.getControllerByName("right");
  86721. }
  86722. return this._rightController;
  86723. },
  86724. enumerable: true,
  86725. configurable: true
  86726. });
  86727. ;
  86728. /**
  86729. * Casts a ray forward from the vrCamera's gaze.
  86730. * @param length Length of the ray (default: 100)
  86731. * @returns the ray corrisponding to the gaze
  86732. */
  86733. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  86734. if (length === void 0) { length = 100; }
  86735. if (this.leftCamera) {
  86736. // Use left eye to avoid computation to compute center on every call
  86737. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  86738. }
  86739. else {
  86740. return _super.prototype.getForwardRay.call(this, length);
  86741. }
  86742. };
  86743. /**
  86744. * Updates the camera based on device's frame data
  86745. */
  86746. WebVRFreeCamera.prototype._checkInputs = function () {
  86747. if (this._vrDevice && this._vrDevice.isPresenting) {
  86748. this._vrDevice.getFrameData(this._frameData);
  86749. this.updateFromDevice(this._frameData.pose);
  86750. }
  86751. _super.prototype._checkInputs.call(this);
  86752. };
  86753. /**
  86754. * Updates the poseControlled values based on the input device pose.
  86755. * @param poseData Pose coming from the device
  86756. */
  86757. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  86758. if (poseData && poseData.orientation) {
  86759. this.rawPose = poseData;
  86760. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  86761. if (this.getScene().useRightHandedSystem) {
  86762. this._deviceRoomRotationQuaternion.z *= -1;
  86763. this._deviceRoomRotationQuaternion.w *= -1;
  86764. }
  86765. if (this.webVROptions.trackPosition && this.rawPose.position) {
  86766. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  86767. if (this.getScene().useRightHandedSystem) {
  86768. this._deviceRoomPosition.z *= -1;
  86769. }
  86770. }
  86771. }
  86772. };
  86773. /**
  86774. * WebVR's attach control will start broadcasting frames to the device.
  86775. * Note that in certain browsers (chrome for example) this function must be called
  86776. * within a user-interaction callback. Example:
  86777. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  86778. *
  86779. * @param element html element to attach the vrDevice to
  86780. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  86781. */
  86782. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  86783. _super.prototype.attachControl.call(this, element, noPreventDefault);
  86784. this._attached = true;
  86785. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  86786. if (this._vrDevice) {
  86787. this.getEngine().enableVR();
  86788. }
  86789. };
  86790. /**
  86791. * Detaches the camera from the html element and disables VR
  86792. *
  86793. * @param element html element to detach from
  86794. */
  86795. WebVRFreeCamera.prototype.detachControl = function (element) {
  86796. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  86797. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  86798. _super.prototype.detachControl.call(this, element);
  86799. this._attached = false;
  86800. this.getEngine().disableVR();
  86801. };
  86802. /**
  86803. * @returns the name of this class
  86804. */
  86805. WebVRFreeCamera.prototype.getClassName = function () {
  86806. return "WebVRFreeCamera";
  86807. };
  86808. /**
  86809. * Calls resetPose on the vrDisplay
  86810. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  86811. */
  86812. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  86813. //uses the vrDisplay's "resetPose()".
  86814. //pitch and roll won't be affected.
  86815. this._vrDevice.resetPose();
  86816. };
  86817. /**
  86818. * Updates the rig cameras (left and right eye)
  86819. */
  86820. WebVRFreeCamera.prototype._updateRigCameras = function () {
  86821. var camLeft = this._rigCameras[0];
  86822. var camRight = this._rigCameras[1];
  86823. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  86824. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  86825. camLeft.position.copyFrom(this._deviceRoomPosition);
  86826. camRight.position.copyFrom(this._deviceRoomPosition);
  86827. };
  86828. /**
  86829. * Updates the cached values of the camera
  86830. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  86831. */
  86832. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  86833. var _this = this;
  86834. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  86835. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  86836. if (!this.updateCacheCalled) {
  86837. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  86838. this.updateCacheCalled = true;
  86839. this.update();
  86840. }
  86841. // Set working vector to the device position in room space rotated by the new rotation
  86842. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  86843. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  86844. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  86845. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  86846. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  86847. // Add translation from anchor position
  86848. this._deviceToWorld.getTranslationToRef(this._workingVector);
  86849. this._workingVector.addInPlace(this.position);
  86850. this._workingVector.subtractInPlace(this._cache.position);
  86851. this._deviceToWorld.setTranslation(this._workingVector);
  86852. // Set an inverted matrix to be used when updating the camera
  86853. this._deviceToWorld.invertToRef(this._worldToDevice);
  86854. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  86855. this.controllers.forEach(function (controller) {
  86856. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  86857. controller.update();
  86858. });
  86859. }
  86860. if (!ignoreParentClass) {
  86861. _super.prototype._updateCache.call(this);
  86862. }
  86863. this.updateCacheCalled = false;
  86864. };
  86865. /**
  86866. * Updates the current device position and rotation in the babylon world
  86867. */
  86868. WebVRFreeCamera.prototype.update = function () {
  86869. // Get current device position in babylon world
  86870. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  86871. // Get current device rotation in babylon world
  86872. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  86873. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  86874. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  86875. _super.prototype.update.call(this);
  86876. };
  86877. /**
  86878. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  86879. * @returns an identity matrix
  86880. */
  86881. WebVRFreeCamera.prototype._getViewMatrix = function () {
  86882. return BABYLON.Matrix.Identity();
  86883. };
  86884. /**
  86885. * This function is called by the two RIG cameras.
  86886. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  86887. */
  86888. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  86889. var _this = this;
  86890. // Update the parent camera prior to using a child camera to avoid desynchronization
  86891. var parentCamera = this._cameraRigParams["parentCamera"];
  86892. parentCamera._updateCache();
  86893. //WebVR 1.1
  86894. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  86895. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  86896. if (!this.getScene().useRightHandedSystem) {
  86897. [2, 6, 8, 9, 14].forEach(function (num) {
  86898. _this._webvrViewMatrix.m[num] *= -1;
  86899. });
  86900. }
  86901. // update the camera rotation matrix
  86902. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  86903. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  86904. // Computing target and final matrix
  86905. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  86906. // should the view matrix be updated with scale and position offset?
  86907. if (parentCamera.deviceScaleFactor !== 1) {
  86908. this._webvrViewMatrix.invert();
  86909. // scale the position, if set
  86910. if (parentCamera.deviceScaleFactor) {
  86911. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  86912. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  86913. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  86914. }
  86915. this._webvrViewMatrix.invert();
  86916. }
  86917. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  86918. // Compute global position
  86919. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  86920. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  86921. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  86922. this._workingMatrix.getTranslationToRef(this._globalPosition);
  86923. this._markSyncedWithParent();
  86924. return this._webvrViewMatrix;
  86925. };
  86926. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  86927. var _this = this;
  86928. var parentCamera = this.parent;
  86929. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  86930. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  86931. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  86932. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  86933. //babylon compatible matrix
  86934. if (!this.getScene().useRightHandedSystem) {
  86935. [8, 9, 10, 11].forEach(function (num) {
  86936. _this._projectionMatrix.m[num] *= -1;
  86937. });
  86938. }
  86939. return this._projectionMatrix;
  86940. };
  86941. /**
  86942. * Initializes the controllers and their meshes
  86943. */
  86944. WebVRFreeCamera.prototype.initControllers = function () {
  86945. var _this = this;
  86946. this.controllers = [];
  86947. var manager = this.getScene().gamepadManager;
  86948. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  86949. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  86950. var webVrController = gamepad;
  86951. if (webVrController.defaultModel) {
  86952. webVrController.defaultModel.setEnabled(false);
  86953. }
  86954. if (webVrController.hand === "right") {
  86955. _this._rightController = null;
  86956. }
  86957. if (webVrController.hand === "left") {
  86958. _this._leftController = null;
  86959. }
  86960. var controllerIndex = _this.controllers.indexOf(webVrController);
  86961. if (controllerIndex !== -1) {
  86962. _this.controllers.splice(controllerIndex, 1);
  86963. }
  86964. }
  86965. });
  86966. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  86967. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  86968. var webVrController_1 = gamepad;
  86969. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  86970. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  86971. if (_this.webVROptions.controllerMeshes) {
  86972. if (webVrController_1.defaultModel) {
  86973. webVrController_1.defaultModel.setEnabled(true);
  86974. }
  86975. else {
  86976. // Load the meshes
  86977. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  86978. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  86979. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  86980. if (_this.webVROptions.defaultLightingOnControllers) {
  86981. if (!_this._lightOnControllers) {
  86982. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  86983. }
  86984. var activateLightOnSubMeshes_1 = function (mesh, light) {
  86985. var children = mesh.getChildren();
  86986. if (children.length !== 0) {
  86987. children.forEach(function (mesh) {
  86988. light.includedOnlyMeshes.push(mesh);
  86989. activateLightOnSubMeshes_1(mesh, light);
  86990. });
  86991. }
  86992. };
  86993. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  86994. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  86995. }
  86996. });
  86997. }
  86998. }
  86999. webVrController_1.attachToPoseControlledCamera(_this);
  87000. // since this is async - sanity check. Is the controller already stored?
  87001. if (_this.controllers.indexOf(webVrController_1) === -1) {
  87002. //add to the controllers array
  87003. _this.controllers.push(webVrController_1);
  87004. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  87005. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  87006. // So we're overriding setting left & right manually to be sure
  87007. var firstViveWandDetected = false;
  87008. for (var i = 0; i < _this.controllers.length; i++) {
  87009. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  87010. if (!firstViveWandDetected) {
  87011. firstViveWandDetected = true;
  87012. _this.controllers[i].hand = "left";
  87013. }
  87014. else {
  87015. _this.controllers[i].hand = "right";
  87016. }
  87017. }
  87018. }
  87019. //did we find enough controllers? Great! let the developer know.
  87020. if (_this.controllers.length >= 2) {
  87021. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  87022. }
  87023. }
  87024. }
  87025. });
  87026. };
  87027. return WebVRFreeCamera;
  87028. }(BABYLON.FreeCamera));
  87029. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  87030. })(BABYLON || (BABYLON = {}));
  87031. //# sourceMappingURL=babylon.webVRCamera.js.map
  87032. var BABYLON;
  87033. (function (BABYLON) {
  87034. // We're mainly based on the logic defined into the FreeCamera code
  87035. /**
  87036. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  87037. * being tilted forward or back and left or right.
  87038. */
  87039. var DeviceOrientationCamera = /** @class */ (function (_super) {
  87040. __extends(DeviceOrientationCamera, _super);
  87041. /**
  87042. * Creates a new device orientation camera
  87043. * @param name The name of the camera
  87044. * @param position The start position camera
  87045. * @param scene The scene the camera belongs to
  87046. */
  87047. function DeviceOrientationCamera(name, position, scene) {
  87048. var _this = _super.call(this, name, position, scene) || this;
  87049. _this._quaternionCache = new BABYLON.Quaternion();
  87050. _this.inputs.addDeviceOrientation();
  87051. return _this;
  87052. }
  87053. /**
  87054. * Gets the current instance class name ("DeviceOrientationCamera").
  87055. * This helps avoiding instanceof at run time.
  87056. * @returns the class name
  87057. */
  87058. DeviceOrientationCamera.prototype.getClassName = function () {
  87059. return "DeviceOrientationCamera";
  87060. };
  87061. /**
  87062. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  87063. */
  87064. DeviceOrientationCamera.prototype._checkInputs = function () {
  87065. _super.prototype._checkInputs.call(this);
  87066. this._quaternionCache.copyFrom(this.rotationQuaternion);
  87067. if (this._initialQuaternion) {
  87068. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  87069. }
  87070. };
  87071. /**
  87072. * Reset the camera to its default orientation on the specified axis only.
  87073. * @param axis The axis to reset
  87074. */
  87075. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  87076. var _this = this;
  87077. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  87078. //can only work if this camera has a rotation quaternion already.
  87079. if (!this.rotationQuaternion)
  87080. return;
  87081. if (!this._initialQuaternion) {
  87082. this._initialQuaternion = new BABYLON.Quaternion();
  87083. }
  87084. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  87085. ['x', 'y', 'z'].forEach(function (axisName) {
  87086. if (!axis[axisName]) {
  87087. _this._initialQuaternion[axisName] = 0;
  87088. }
  87089. else {
  87090. _this._initialQuaternion[axisName] *= -1;
  87091. }
  87092. });
  87093. this._initialQuaternion.normalize();
  87094. //force rotation update
  87095. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  87096. };
  87097. return DeviceOrientationCamera;
  87098. }(BABYLON.FreeCamera));
  87099. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  87100. })(BABYLON || (BABYLON = {}));
  87101. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  87102. var BABYLON;
  87103. (function (BABYLON) {
  87104. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  87105. __extends(VRDeviceOrientationFreeCamera, _super);
  87106. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  87107. if (compensateDistortion === void 0) { compensateDistortion = true; }
  87108. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  87109. var _this = _super.call(this, name, position, scene) || this;
  87110. vrCameraMetrics.compensateDistortion = compensateDistortion;
  87111. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  87112. return _this;
  87113. }
  87114. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  87115. return "VRDeviceOrientationFreeCamera";
  87116. };
  87117. return VRDeviceOrientationFreeCamera;
  87118. }(BABYLON.DeviceOrientationCamera));
  87119. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  87120. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  87121. __extends(VRDeviceOrientationGamepadCamera, _super);
  87122. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  87123. if (compensateDistortion === void 0) { compensateDistortion = true; }
  87124. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  87125. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  87126. _this.inputs.addGamepad();
  87127. return _this;
  87128. }
  87129. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  87130. return "VRDeviceOrientationGamepadCamera";
  87131. };
  87132. return VRDeviceOrientationGamepadCamera;
  87133. }(VRDeviceOrientationFreeCamera));
  87134. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  87135. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  87136. __extends(VRDeviceOrientationArcRotateCamera, _super);
  87137. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  87138. if (compensateDistortion === void 0) { compensateDistortion = true; }
  87139. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  87140. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  87141. vrCameraMetrics.compensateDistortion = compensateDistortion;
  87142. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  87143. _this.inputs.addVRDeviceOrientation();
  87144. return _this;
  87145. }
  87146. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  87147. return "VRDeviceOrientationArcRotateCamera";
  87148. };
  87149. return VRDeviceOrientationArcRotateCamera;
  87150. }(BABYLON.ArcRotateCamera));
  87151. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  87152. })(BABYLON || (BABYLON = {}));
  87153. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  87154. var BABYLON;
  87155. (function (BABYLON) {
  87156. /**
  87157. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  87158. */
  87159. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  87160. __extends(AnaglyphFreeCamera, _super);
  87161. /**
  87162. * Creates a new AnaglyphFreeCamera
  87163. * @param name defines camera name
  87164. * @param position defines initial position
  87165. * @param interaxialDistance defines distance between each color axis
  87166. * @param scene defines the hosting scene
  87167. */
  87168. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  87169. var _this = _super.call(this, name, position, scene) || this;
  87170. _this.interaxialDistance = interaxialDistance;
  87171. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87172. return _this;
  87173. }
  87174. /**
  87175. * Gets camera class name
  87176. * @returns AnaglyphFreeCamera
  87177. */
  87178. AnaglyphFreeCamera.prototype.getClassName = function () {
  87179. return "AnaglyphFreeCamera";
  87180. };
  87181. return AnaglyphFreeCamera;
  87182. }(BABYLON.FreeCamera));
  87183. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  87184. /**
  87185. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  87186. */
  87187. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  87188. __extends(AnaglyphArcRotateCamera, _super);
  87189. /**
  87190. * Creates a new AnaglyphArcRotateCamera
  87191. * @param name defines camera name
  87192. * @param alpha defines alpha angle (in radians)
  87193. * @param beta defines beta angle (in radians)
  87194. * @param radius defines radius
  87195. * @param target defines camera target
  87196. * @param interaxialDistance defines distance between each color axis
  87197. * @param scene defines the hosting scene
  87198. */
  87199. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  87200. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  87201. _this.interaxialDistance = interaxialDistance;
  87202. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87203. return _this;
  87204. }
  87205. /**
  87206. * Gets camera class name
  87207. * @returns AnaglyphArcRotateCamera
  87208. */
  87209. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  87210. return "AnaglyphArcRotateCamera";
  87211. };
  87212. return AnaglyphArcRotateCamera;
  87213. }(BABYLON.ArcRotateCamera));
  87214. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  87215. /**
  87216. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  87217. */
  87218. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  87219. __extends(AnaglyphGamepadCamera, _super);
  87220. /**
  87221. * Creates a new AnaglyphGamepadCamera
  87222. * @param name defines camera name
  87223. * @param position defines initial position
  87224. * @param interaxialDistance defines distance between each color axis
  87225. * @param scene defines the hosting scene
  87226. */
  87227. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  87228. var _this = _super.call(this, name, position, scene) || this;
  87229. _this.interaxialDistance = interaxialDistance;
  87230. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87231. return _this;
  87232. }
  87233. /**
  87234. * Gets camera class name
  87235. * @returns AnaglyphGamepadCamera
  87236. */
  87237. AnaglyphGamepadCamera.prototype.getClassName = function () {
  87238. return "AnaglyphGamepadCamera";
  87239. };
  87240. return AnaglyphGamepadCamera;
  87241. }(BABYLON.GamepadCamera));
  87242. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  87243. /**
  87244. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  87245. */
  87246. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  87247. __extends(AnaglyphUniversalCamera, _super);
  87248. /**
  87249. * Creates a new AnaglyphUniversalCamera
  87250. * @param name defines camera name
  87251. * @param position defines initial position
  87252. * @param interaxialDistance defines distance between each color axis
  87253. * @param scene defines the hosting scene
  87254. */
  87255. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  87256. var _this = _super.call(this, name, position, scene) || this;
  87257. _this.interaxialDistance = interaxialDistance;
  87258. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87259. return _this;
  87260. }
  87261. /**
  87262. * Gets camera class name
  87263. * @returns AnaglyphUniversalCamera
  87264. */
  87265. AnaglyphUniversalCamera.prototype.getClassName = function () {
  87266. return "AnaglyphUniversalCamera";
  87267. };
  87268. return AnaglyphUniversalCamera;
  87269. }(BABYLON.UniversalCamera));
  87270. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  87271. /**
  87272. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  87273. */
  87274. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  87275. __extends(StereoscopicFreeCamera, _super);
  87276. /**
  87277. * Creates a new StereoscopicFreeCamera
  87278. * @param name defines camera name
  87279. * @param position defines initial position
  87280. * @param interaxialDistance defines distance between each color axis
  87281. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  87282. * @param scene defines the hosting scene
  87283. */
  87284. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  87285. var _this = _super.call(this, name, position, scene) || this;
  87286. _this.interaxialDistance = interaxialDistance;
  87287. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  87288. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  87289. return _this;
  87290. }
  87291. /**
  87292. * Gets camera class name
  87293. * @returns StereoscopicFreeCamera
  87294. */
  87295. StereoscopicFreeCamera.prototype.getClassName = function () {
  87296. return "StereoscopicFreeCamera";
  87297. };
  87298. return StereoscopicFreeCamera;
  87299. }(BABYLON.FreeCamera));
  87300. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  87301. /**
  87302. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  87303. */
  87304. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  87305. __extends(StereoscopicArcRotateCamera, _super);
  87306. /**
  87307. * Creates a new StereoscopicArcRotateCamera
  87308. * @param name defines camera name
  87309. * @param alpha defines alpha angle (in radians)
  87310. * @param beta defines beta angle (in radians)
  87311. * @param radius defines radius
  87312. * @param target defines camera target
  87313. * @param interaxialDistance defines distance between each color axis
  87314. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  87315. * @param scene defines the hosting scene
  87316. */
  87317. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  87318. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  87319. _this.interaxialDistance = interaxialDistance;
  87320. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  87321. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  87322. return _this;
  87323. }
  87324. /**
  87325. * Gets camera class name
  87326. * @returns StereoscopicArcRotateCamera
  87327. */
  87328. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  87329. return "StereoscopicArcRotateCamera";
  87330. };
  87331. return StereoscopicArcRotateCamera;
  87332. }(BABYLON.ArcRotateCamera));
  87333. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  87334. /**
  87335. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  87336. */
  87337. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  87338. __extends(StereoscopicGamepadCamera, _super);
  87339. /**
  87340. * Creates a new StereoscopicGamepadCamera
  87341. * @param name defines camera name
  87342. * @param position defines initial position
  87343. * @param interaxialDistance defines distance between each color axis
  87344. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  87345. * @param scene defines the hosting scene
  87346. */
  87347. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  87348. var _this = _super.call(this, name, position, scene) || this;
  87349. _this.interaxialDistance = interaxialDistance;
  87350. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  87351. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  87352. return _this;
  87353. }
  87354. /**
  87355. * Gets camera class name
  87356. * @returns StereoscopicGamepadCamera
  87357. */
  87358. StereoscopicGamepadCamera.prototype.getClassName = function () {
  87359. return "StereoscopicGamepadCamera";
  87360. };
  87361. return StereoscopicGamepadCamera;
  87362. }(BABYLON.GamepadCamera));
  87363. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  87364. /**
  87365. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  87366. */
  87367. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  87368. __extends(StereoscopicUniversalCamera, _super);
  87369. /**
  87370. * Creates a new StereoscopicUniversalCamera
  87371. * @param name defines camera name
  87372. * @param position defines initial position
  87373. * @param interaxialDistance defines distance between each color axis
  87374. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  87375. * @param scene defines the hosting scene
  87376. */
  87377. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  87378. var _this = _super.call(this, name, position, scene) || this;
  87379. _this.interaxialDistance = interaxialDistance;
  87380. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  87381. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  87382. return _this;
  87383. }
  87384. /**
  87385. * Gets camera class name
  87386. * @returns StereoscopicUniversalCamera
  87387. */
  87388. StereoscopicUniversalCamera.prototype.getClassName = function () {
  87389. return "StereoscopicUniversalCamera";
  87390. };
  87391. return StereoscopicUniversalCamera;
  87392. }(BABYLON.UniversalCamera));
  87393. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  87394. })(BABYLON || (BABYLON = {}));
  87395. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  87396. var BABYLON;
  87397. (function (BABYLON) {
  87398. var VRExperienceHelperGazer = /** @class */ (function () {
  87399. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  87400. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  87401. this.scene = scene;
  87402. this._pointerDownOnMeshAsked = false;
  87403. this._isActionableMesh = false;
  87404. this._teleportationRequestInitiated = false;
  87405. this._teleportationBackRequestInitiated = false;
  87406. this._rotationRightAsked = false;
  87407. this._rotationLeftAsked = false;
  87408. this._dpadPressed = true;
  87409. this._activePointer = false;
  87410. this._id = VRExperienceHelperGazer._idCounter++;
  87411. // Gaze tracker
  87412. if (!gazeTrackerToClone) {
  87413. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  87414. this._gazeTracker.bakeCurrentTransformIntoVertices();
  87415. this._gazeTracker.isPickable = false;
  87416. this._gazeTracker.isVisible = false;
  87417. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  87418. targetMat.specularColor = BABYLON.Color3.Black();
  87419. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  87420. targetMat.backFaceCulling = false;
  87421. this._gazeTracker.material = targetMat;
  87422. }
  87423. else {
  87424. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  87425. }
  87426. }
  87427. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  87428. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  87429. };
  87430. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  87431. this._pointerDownOnMeshAsked = true;
  87432. if (this._currentMeshSelected && this._currentHit) {
  87433. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  87434. }
  87435. };
  87436. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  87437. if (this._currentMeshSelected && this._currentHit) {
  87438. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  87439. }
  87440. this._pointerDownOnMeshAsked = false;
  87441. };
  87442. VRExperienceHelperGazer.prototype._activatePointer = function () {
  87443. this._activePointer = true;
  87444. };
  87445. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  87446. this._activePointer = false;
  87447. };
  87448. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  87449. if (distance === void 0) { distance = 100; }
  87450. };
  87451. VRExperienceHelperGazer.prototype.dispose = function () {
  87452. this._interactionsEnabled = false;
  87453. this._teleportationEnabled = false;
  87454. if (this._gazeTracker) {
  87455. this._gazeTracker.dispose();
  87456. }
  87457. };
  87458. VRExperienceHelperGazer._idCounter = 0;
  87459. return VRExperienceHelperGazer;
  87460. }());
  87461. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  87462. __extends(VRExperienceHelperControllerGazer, _super);
  87463. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  87464. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  87465. _this.webVRController = webVRController;
  87466. // Laser pointer
  87467. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  87468. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  87469. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  87470. laserPointerMaterial.alpha = 0.6;
  87471. _this._laserPointer.material = laserPointerMaterial;
  87472. _this._laserPointer.rotation.x = Math.PI / 2;
  87473. _this._laserPointer.position.z = -0.5;
  87474. _this._laserPointer.isVisible = false;
  87475. if (!webVRController.mesh) {
  87476. // Create an empty mesh that is used prior to loading the high quality model
  87477. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  87478. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  87479. preloadPointerPose.rotation.x = -0.7;
  87480. preloadMesh.addChild(preloadPointerPose);
  87481. webVRController.attachToMesh(preloadMesh);
  87482. }
  87483. _this._setLaserPointerParent(webVRController.mesh);
  87484. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  87485. _this._setLaserPointerParent(mesh);
  87486. });
  87487. return _this;
  87488. }
  87489. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  87490. return this.webVRController.getForwardRay(length);
  87491. };
  87492. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  87493. _super.prototype._activatePointer.call(this);
  87494. this._laserPointer.isVisible = true;
  87495. };
  87496. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  87497. _super.prototype._deactivatePointer.call(this);
  87498. this._laserPointer.isVisible = false;
  87499. };
  87500. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  87501. this._laserPointer.material.emissiveColor = color;
  87502. };
  87503. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  87504. var makeNotPick = function (root) {
  87505. root.name += " laserPointer";
  87506. root.getChildMeshes().forEach(function (c) {
  87507. makeNotPick(c);
  87508. });
  87509. };
  87510. makeNotPick(mesh);
  87511. var childMeshes = mesh.getChildMeshes();
  87512. this.webVRController._pointingPoseNode = null;
  87513. for (var i = 0; i < childMeshes.length; i++) {
  87514. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  87515. mesh = childMeshes[i];
  87516. this.webVRController._pointingPoseNode = mesh;
  87517. break;
  87518. }
  87519. }
  87520. this._laserPointer.parent = mesh;
  87521. };
  87522. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  87523. if (distance === void 0) { distance = 100; }
  87524. this._laserPointer.scaling.y = distance;
  87525. this._laserPointer.position.z = -distance / 2;
  87526. };
  87527. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  87528. _super.prototype.dispose.call(this);
  87529. this._laserPointer.dispose();
  87530. if (this._meshAttachedObserver) {
  87531. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  87532. }
  87533. };
  87534. return VRExperienceHelperControllerGazer;
  87535. }(VRExperienceHelperGazer));
  87536. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  87537. __extends(VRExperienceHelperCameraGazer, _super);
  87538. function VRExperienceHelperCameraGazer(getCamera, scene) {
  87539. var _this = _super.call(this, scene) || this;
  87540. _this.getCamera = getCamera;
  87541. return _this;
  87542. }
  87543. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  87544. var camera = this.getCamera();
  87545. if (camera) {
  87546. return camera.getForwardRay(length);
  87547. }
  87548. else {
  87549. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  87550. }
  87551. };
  87552. return VRExperienceHelperCameraGazer;
  87553. }(VRExperienceHelperGazer));
  87554. /**
  87555. * Helps to quickly add VR support to an existing scene.
  87556. * See http://doc.babylonjs.com/how_to/webvr_helper
  87557. */
  87558. var VRExperienceHelper = /** @class */ (function () {
  87559. /**
  87560. * Instantiates a VRExperienceHelper.
  87561. * Helps to quickly add VR support to an existing scene.
  87562. * @param scene The scene the VRExperienceHelper belongs to.
  87563. * @param webVROptions Options to modify the vr experience helper's behavior.
  87564. */
  87565. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  87566. if (webVROptions === void 0) { webVROptions = {}; }
  87567. var _this = this;
  87568. this.webVROptions = webVROptions;
  87569. // Can the system support WebVR, even if a headset isn't plugged in?
  87570. this._webVRsupported = false;
  87571. // If WebVR is supported, is a headset plugged in and are we ready to present?
  87572. this._webVRready = false;
  87573. // Are we waiting for the requestPresent callback to complete?
  87574. this._webVRrequesting = false;
  87575. // Are we presenting to the headset right now?
  87576. this._webVRpresenting = false;
  87577. // Are we presenting in the fullscreen fallback?
  87578. this._fullscreenVRpresenting = false;
  87579. /**
  87580. * Observable raised when entering VR.
  87581. */
  87582. this.onEnteringVRObservable = new BABYLON.Observable();
  87583. /**
  87584. * Observable raised when exiting VR.
  87585. */
  87586. this.onExitingVRObservable = new BABYLON.Observable();
  87587. /**
  87588. * Observable raised when controller mesh is loaded.
  87589. */
  87590. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  87591. this._useCustomVRButton = false;
  87592. this._teleportationRequested = false;
  87593. this._teleportActive = false;
  87594. this._floorMeshesCollection = [];
  87595. this._rotationAllowed = true;
  87596. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  87597. this._isDefaultTeleportationTarget = true;
  87598. this._teleportationFillColor = "#444444";
  87599. this._teleportationBorderColor = "#FFFFFF";
  87600. this._rotationAngle = 0;
  87601. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  87602. this._padSensibilityUp = 0.65;
  87603. this._padSensibilityDown = 0.35;
  87604. this.leftController = null;
  87605. this.rightController = null;
  87606. /**
  87607. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  87608. */
  87609. this.onNewMeshSelected = new BABYLON.Observable();
  87610. /**
  87611. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  87612. */
  87613. this.onNewMeshPicked = new BABYLON.Observable();
  87614. /**
  87615. * Observable raised before camera teleportation
  87616. */
  87617. this.onBeforeCameraTeleport = new BABYLON.Observable();
  87618. /**
  87619. * Observable raised after camera teleportation
  87620. */
  87621. this.onAfterCameraTeleport = new BABYLON.Observable();
  87622. /**
  87623. * Observable raised when current selected mesh gets unselected
  87624. */
  87625. this.onSelectedMeshUnselected = new BABYLON.Observable();
  87626. /**
  87627. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  87628. */
  87629. this.teleportationEnabled = true;
  87630. this._teleportationInitialized = false;
  87631. this._interactionsEnabled = false;
  87632. this._interactionsRequested = false;
  87633. this._displayGaze = true;
  87634. this._displayLaserPointer = true;
  87635. this._onResize = function () {
  87636. _this.moveButtonToBottomRight();
  87637. if (_this._fullscreenVRpresenting && _this._webVRready) {
  87638. _this.exitVR();
  87639. }
  87640. };
  87641. this._onFullscreenChange = function () {
  87642. if (document.fullscreen !== undefined) {
  87643. _this._fullscreenVRpresenting = document.fullscreen;
  87644. }
  87645. else if (document.mozFullScreen !== undefined) {
  87646. _this._fullscreenVRpresenting = document.mozFullScreen;
  87647. }
  87648. else if (document.webkitIsFullScreen !== undefined) {
  87649. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  87650. }
  87651. else if (document.msIsFullScreen !== undefined) {
  87652. _this._fullscreenVRpresenting = document.msIsFullScreen;
  87653. }
  87654. if (!_this._fullscreenVRpresenting && _this._canvas) {
  87655. _this.exitVR();
  87656. if (!_this._useCustomVRButton) {
  87657. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  87658. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  87659. }
  87660. }
  87661. };
  87662. this.beforeRender = function () {
  87663. if (_this.leftController && _this.leftController._activePointer) {
  87664. _this._castRayAndSelectObject(_this.leftController);
  87665. }
  87666. if (_this.rightController && _this.rightController._activePointer) {
  87667. _this._castRayAndSelectObject(_this.rightController);
  87668. }
  87669. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  87670. _this._castRayAndSelectObject(_this._cameraGazer);
  87671. }
  87672. else {
  87673. _this._cameraGazer._gazeTracker.isVisible = false;
  87674. }
  87675. };
  87676. this._onNewGamepadConnected = function (gamepad) {
  87677. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  87678. if (gamepad.leftStick) {
  87679. gamepad.onleftstickchanged(function (stickValues) {
  87680. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  87681. // Listening to classic/xbox gamepad only if no VR controller is active
  87682. if ((!_this.leftController && !_this.rightController) ||
  87683. ((_this.leftController && !_this.leftController._activePointer) &&
  87684. (_this.rightController && !_this.rightController._activePointer))) {
  87685. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  87686. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  87687. }
  87688. }
  87689. });
  87690. }
  87691. if (gamepad.rightStick) {
  87692. gamepad.onrightstickchanged(function (stickValues) {
  87693. if (_this._teleportationInitialized) {
  87694. _this._checkRotate(stickValues, _this._cameraGazer);
  87695. }
  87696. });
  87697. }
  87698. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  87699. gamepad.onbuttondown(function (buttonPressed) {
  87700. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  87701. _this._cameraGazer._selectionPointerDown();
  87702. }
  87703. });
  87704. gamepad.onbuttonup(function (buttonPressed) {
  87705. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  87706. _this._cameraGazer._selectionPointerUp();
  87707. }
  87708. });
  87709. }
  87710. }
  87711. else {
  87712. var webVRController = gamepad;
  87713. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  87714. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  87715. _this.rightController = controller;
  87716. }
  87717. else {
  87718. _this.leftController = controller;
  87719. }
  87720. _this._tryEnableInteractionOnController(controller);
  87721. }
  87722. };
  87723. // 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
  87724. this._tryEnableInteractionOnController = function (controller) {
  87725. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  87726. _this._enableInteractionOnController(controller);
  87727. }
  87728. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  87729. _this._enableTeleportationOnController(controller);
  87730. }
  87731. };
  87732. this._onNewGamepadDisconnected = function (gamepad) {
  87733. if (gamepad instanceof BABYLON.WebVRController) {
  87734. if (gamepad.hand === "left" && _this.leftController != null) {
  87735. _this.leftController.dispose();
  87736. _this.leftController = null;
  87737. }
  87738. if (gamepad.hand === "right" && _this.rightController != null) {
  87739. _this.rightController.dispose();
  87740. _this.rightController = null;
  87741. }
  87742. }
  87743. };
  87744. this._workingVector = BABYLON.Vector3.Zero();
  87745. this._workingQuaternion = BABYLON.Quaternion.Identity();
  87746. this._workingMatrix = BABYLON.Matrix.Identity();
  87747. this._scene = scene;
  87748. this._canvas = scene.getEngine().getRenderingCanvas();
  87749. // Parse options
  87750. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  87751. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  87752. }
  87753. if (webVROptions.createDeviceOrientationCamera === undefined) {
  87754. webVROptions.createDeviceOrientationCamera = true;
  87755. }
  87756. if (webVROptions.defaultHeight === undefined) {
  87757. webVROptions.defaultHeight = 1.7;
  87758. }
  87759. if (webVROptions.useCustomVRButton) {
  87760. this._useCustomVRButton = true;
  87761. if (webVROptions.customVRButton) {
  87762. this._btnVR = webVROptions.customVRButton;
  87763. }
  87764. }
  87765. if (webVROptions.rayLength) {
  87766. this._rayLength = webVROptions.rayLength;
  87767. }
  87768. this._defaultHeight = webVROptions.defaultHeight;
  87769. if (webVROptions.positionScale) {
  87770. this._rayLength *= webVROptions.positionScale;
  87771. this._defaultHeight *= webVROptions.positionScale;
  87772. }
  87773. // Set position
  87774. if (this._scene.activeCamera) {
  87775. this._position = this._scene.activeCamera.position.clone();
  87776. }
  87777. else {
  87778. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  87779. }
  87780. // Set non-vr camera
  87781. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  87782. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  87783. // Copy data from existing camera
  87784. if (this._scene.activeCamera) {
  87785. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  87786. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  87787. // Set rotation from previous camera
  87788. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  87789. var targetCamera = this._scene.activeCamera;
  87790. if (targetCamera.rotationQuaternion) {
  87791. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  87792. }
  87793. else {
  87794. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  87795. }
  87796. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  87797. }
  87798. }
  87799. this._scene.activeCamera = this._deviceOrientationCamera;
  87800. if (this._canvas) {
  87801. this._scene.activeCamera.attachControl(this._canvas);
  87802. }
  87803. }
  87804. else {
  87805. this._existingCamera = this._scene.activeCamera;
  87806. }
  87807. // Create VR cameras
  87808. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  87809. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  87810. }
  87811. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  87812. this._webVRCamera.useStandingMatrix();
  87813. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  87814. // Create default button
  87815. if (!this._useCustomVRButton) {
  87816. this._btnVR = document.createElement("BUTTON");
  87817. this._btnVR.className = "babylonVRicon";
  87818. this._btnVR.id = "babylonVRiconbtn";
  87819. this._btnVR.title = "Click to switch to VR";
  87820. 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) }";
  87821. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  87822. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  87823. // css += ".babylonVRicon.vrdisplaysupported { }";
  87824. // css += ".babylonVRicon.vrdisplayready { }";
  87825. // css += ".babylonVRicon.vrdisplayrequesting { }";
  87826. var style = document.createElement('style');
  87827. style.appendChild(document.createTextNode(css));
  87828. document.getElementsByTagName('head')[0].appendChild(style);
  87829. this.moveButtonToBottomRight();
  87830. }
  87831. // VR button click event
  87832. if (this._btnVR) {
  87833. this._btnVR.addEventListener("click", function () {
  87834. if (!_this.isInVRMode) {
  87835. _this.enterVR();
  87836. }
  87837. else {
  87838. _this.exitVR();
  87839. }
  87840. });
  87841. }
  87842. // Window events
  87843. window.addEventListener("resize", this._onResize);
  87844. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  87845. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  87846. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  87847. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  87848. // Display vr button when headset is connected
  87849. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  87850. this.displayVRButton();
  87851. }
  87852. else {
  87853. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  87854. if (e.vrDisplay) {
  87855. _this.displayVRButton();
  87856. }
  87857. });
  87858. }
  87859. // Exiting VR mode using 'ESC' key on desktop
  87860. this._onKeyDown = function (event) {
  87861. if (event.keyCode === 27 && _this.isInVRMode) {
  87862. _this.exitVR();
  87863. }
  87864. };
  87865. document.addEventListener("keydown", this._onKeyDown);
  87866. // Exiting VR mode double tapping the touch screen
  87867. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  87868. if (_this.isInVRMode) {
  87869. _this.exitVR();
  87870. if (_this._fullscreenVRpresenting) {
  87871. _this._scene.getEngine().switchFullscreen(true);
  87872. }
  87873. }
  87874. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  87875. // Listen for WebVR display changes
  87876. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  87877. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  87878. this._onVRRequestPresentStart = function () {
  87879. _this._webVRrequesting = true;
  87880. _this.updateButtonVisibility();
  87881. };
  87882. this._onVRRequestPresentComplete = function (success) {
  87883. _this._webVRrequesting = false;
  87884. _this.updateButtonVisibility();
  87885. };
  87886. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  87887. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  87888. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  87889. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  87890. scene.onDisposeObservable.add(function () {
  87891. _this.dispose();
  87892. });
  87893. // Gamepad connection events
  87894. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  87895. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  87896. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  87897. this.updateButtonVisibility();
  87898. //create easing functions
  87899. this._circleEase = new BABYLON.CircleEase();
  87900. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  87901. }
  87902. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  87903. /** Return this.onEnteringVRObservable
  87904. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  87905. */
  87906. get: function () {
  87907. return this.onEnteringVRObservable;
  87908. },
  87909. enumerable: true,
  87910. configurable: true
  87911. });
  87912. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  87913. /** Return this.onExitingVRObservable
  87914. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  87915. */
  87916. get: function () {
  87917. return this.onExitingVRObservable;
  87918. },
  87919. enumerable: true,
  87920. configurable: true
  87921. });
  87922. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  87923. /** Return this.onControllerMeshLoadedObservable
  87924. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  87925. */
  87926. get: function () {
  87927. return this.onControllerMeshLoadedObservable;
  87928. },
  87929. enumerable: true,
  87930. configurable: true
  87931. });
  87932. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  87933. /**
  87934. * The mesh used to display where the user is going to teleport.
  87935. */
  87936. get: function () {
  87937. return this._teleportationTarget;
  87938. },
  87939. /**
  87940. * Sets the mesh to be used to display where the user is going to teleport.
  87941. */
  87942. set: function (value) {
  87943. if (value) {
  87944. value.name = "teleportationTarget";
  87945. this._isDefaultTeleportationTarget = false;
  87946. this._teleportationTarget = value;
  87947. }
  87948. },
  87949. enumerable: true,
  87950. configurable: true
  87951. });
  87952. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  87953. /**
  87954. * The mesh used to display where the user is selecting,
  87955. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  87956. * See http://doc.babylonjs.com/resources/baking_transformations
  87957. */
  87958. get: function () {
  87959. return this._cameraGazer._gazeTracker;
  87960. },
  87961. set: function (value) {
  87962. if (value) {
  87963. this._cameraGazer._gazeTracker = value;
  87964. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  87965. this._cameraGazer._gazeTracker.isPickable = false;
  87966. this._cameraGazer._gazeTracker.isVisible = false;
  87967. this._cameraGazer._gazeTracker.name = "gazeTracker";
  87968. if (this.leftController) {
  87969. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  87970. }
  87971. if (this.rightController) {
  87972. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  87973. }
  87974. }
  87975. },
  87976. enumerable: true,
  87977. configurable: true
  87978. });
  87979. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  87980. /**
  87981. * If the ray of the gaze should be displayed.
  87982. */
  87983. get: function () {
  87984. return this._displayGaze;
  87985. },
  87986. /**
  87987. * Sets if the ray of the gaze should be displayed.
  87988. */
  87989. set: function (value) {
  87990. this._displayGaze = value;
  87991. if (!value) {
  87992. this._cameraGazer._gazeTracker.isVisible = false;
  87993. if (this.leftController) {
  87994. this.leftController._gazeTracker.isVisible = false;
  87995. }
  87996. if (this.rightController) {
  87997. this.rightController._gazeTracker.isVisible = false;
  87998. }
  87999. }
  88000. },
  88001. enumerable: true,
  88002. configurable: true
  88003. });
  88004. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  88005. /**
  88006. * If the ray of the LaserPointer should be displayed.
  88007. */
  88008. get: function () {
  88009. return this._displayLaserPointer;
  88010. },
  88011. /**
  88012. * Sets if the ray of the LaserPointer should be displayed.
  88013. */
  88014. set: function (value) {
  88015. this._displayLaserPointer = value;
  88016. if (!value) {
  88017. if (this.rightController) {
  88018. this.rightController._deactivatePointer();
  88019. this.rightController._gazeTracker.isVisible = false;
  88020. }
  88021. if (this.leftController) {
  88022. this.leftController._deactivatePointer();
  88023. this.leftController._gazeTracker.isVisible = false;
  88024. }
  88025. }
  88026. else {
  88027. if (this.rightController) {
  88028. this.rightController._activatePointer();
  88029. }
  88030. if (this.leftController) {
  88031. this.leftController._activatePointer();
  88032. }
  88033. }
  88034. },
  88035. enumerable: true,
  88036. configurable: true
  88037. });
  88038. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  88039. /**
  88040. * The deviceOrientationCamera used as the camera when not in VR.
  88041. */
  88042. get: function () {
  88043. return this._deviceOrientationCamera;
  88044. },
  88045. enumerable: true,
  88046. configurable: true
  88047. });
  88048. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  88049. /**
  88050. * Based on the current WebVR support, returns the current VR camera used.
  88051. */
  88052. get: function () {
  88053. if (this._webVRready) {
  88054. return this._webVRCamera;
  88055. }
  88056. else {
  88057. return this._scene.activeCamera;
  88058. }
  88059. },
  88060. enumerable: true,
  88061. configurable: true
  88062. });
  88063. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  88064. /**
  88065. * The webVRCamera which is used when in VR.
  88066. */
  88067. get: function () {
  88068. return this._webVRCamera;
  88069. },
  88070. enumerable: true,
  88071. configurable: true
  88072. });
  88073. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  88074. /**
  88075. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  88076. */
  88077. get: function () {
  88078. return this._vrDeviceOrientationCamera;
  88079. },
  88080. enumerable: true,
  88081. configurable: true
  88082. });
  88083. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  88084. get: function () {
  88085. var result = this._cameraGazer._teleportationRequestInitiated
  88086. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  88087. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  88088. return result;
  88089. },
  88090. enumerable: true,
  88091. configurable: true
  88092. });
  88093. // Raised when one of the controller has loaded successfully its associated default mesh
  88094. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  88095. if (this.leftController && this.leftController.webVRController == webVRController) {
  88096. if (webVRController.mesh) {
  88097. this.leftController._setLaserPointerParent(webVRController.mesh);
  88098. }
  88099. }
  88100. if (this.rightController && this.rightController.webVRController == webVRController) {
  88101. if (webVRController.mesh) {
  88102. this.rightController._setLaserPointerParent(webVRController.mesh);
  88103. }
  88104. }
  88105. try {
  88106. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  88107. }
  88108. catch (err) {
  88109. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  88110. }
  88111. };
  88112. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  88113. /**
  88114. * Gets a value indicating if we are currently in VR mode.
  88115. */
  88116. get: function () {
  88117. return this._webVRpresenting || this._fullscreenVRpresenting;
  88118. },
  88119. enumerable: true,
  88120. configurable: true
  88121. });
  88122. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  88123. var vrDisplay = this._scene.getEngine().getVRDevice();
  88124. if (vrDisplay) {
  88125. var wasPresenting = this._webVRpresenting;
  88126. // A VR display is connected
  88127. this._webVRpresenting = vrDisplay.isPresenting;
  88128. if (wasPresenting && !this._webVRpresenting)
  88129. this.exitVR();
  88130. }
  88131. else {
  88132. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  88133. }
  88134. this.updateButtonVisibility();
  88135. };
  88136. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  88137. this._webVRsupported = eventArgs.vrSupported;
  88138. this._webVRready = !!eventArgs.vrDisplay;
  88139. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  88140. this.updateButtonVisibility();
  88141. };
  88142. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  88143. if (this._canvas && !this._useCustomVRButton) {
  88144. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  88145. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  88146. }
  88147. };
  88148. VRExperienceHelper.prototype.displayVRButton = function () {
  88149. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  88150. document.body.appendChild(this._btnVR);
  88151. this._btnVRDisplayed = true;
  88152. }
  88153. };
  88154. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  88155. if (!this._btnVR || this._useCustomVRButton) {
  88156. return;
  88157. }
  88158. this._btnVR.className = "babylonVRicon";
  88159. if (this.isInVRMode) {
  88160. this._btnVR.className += " vrdisplaypresenting";
  88161. }
  88162. else {
  88163. if (this._webVRready)
  88164. this._btnVR.className += " vrdisplayready";
  88165. if (this._webVRsupported)
  88166. this._btnVR.className += " vrdisplaysupported";
  88167. if (this._webVRrequesting)
  88168. this._btnVR.className += " vrdisplayrequesting";
  88169. }
  88170. };
  88171. /**
  88172. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  88173. * Otherwise, will use the fullscreen API.
  88174. */
  88175. VRExperienceHelper.prototype.enterVR = function () {
  88176. if (this.onEnteringVRObservable) {
  88177. try {
  88178. this.onEnteringVRObservable.notifyObservers(this);
  88179. }
  88180. catch (err) {
  88181. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  88182. }
  88183. }
  88184. if (this._scene.activeCamera) {
  88185. this._position = this._scene.activeCamera.position.clone();
  88186. // make sure that we return to the last active camera
  88187. this._existingCamera = this._scene.activeCamera;
  88188. }
  88189. if (this._webVRrequesting)
  88190. return;
  88191. // If WebVR is supported and a headset is connected
  88192. if (this._webVRready) {
  88193. if (!this._webVRpresenting) {
  88194. this._webVRCamera.position = this._position;
  88195. this._scene.activeCamera = this._webVRCamera;
  88196. }
  88197. }
  88198. else if (this._vrDeviceOrientationCamera) {
  88199. this._vrDeviceOrientationCamera.position = this._position;
  88200. if (this._scene.activeCamera) {
  88201. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  88202. }
  88203. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  88204. this._scene.getEngine().switchFullscreen(true);
  88205. this.updateButtonVisibility();
  88206. }
  88207. if (this._scene.activeCamera && this._canvas) {
  88208. this._scene.activeCamera.attachControl(this._canvas);
  88209. }
  88210. if (this._interactionsEnabled) {
  88211. this._scene.registerBeforeRender(this.beforeRender);
  88212. }
  88213. };
  88214. /**
  88215. * Attempt to exit VR, or fullscreen.
  88216. */
  88217. VRExperienceHelper.prototype.exitVR = function () {
  88218. if (this.onExitingVRObservable) {
  88219. try {
  88220. this.onExitingVRObservable.notifyObservers(this);
  88221. }
  88222. catch (err) {
  88223. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  88224. }
  88225. }
  88226. if (this._webVRpresenting) {
  88227. this._scene.getEngine().disableVR();
  88228. }
  88229. if (this._scene.activeCamera) {
  88230. this._position = this._scene.activeCamera.position.clone();
  88231. }
  88232. if (this._deviceOrientationCamera) {
  88233. this._deviceOrientationCamera.position = this._position;
  88234. this._scene.activeCamera = this._deviceOrientationCamera;
  88235. if (this._canvas) {
  88236. this._scene.activeCamera.attachControl(this._canvas);
  88237. }
  88238. }
  88239. else if (this._existingCamera) {
  88240. this._existingCamera.position = this._position;
  88241. this._scene.activeCamera = this._existingCamera;
  88242. }
  88243. this.updateButtonVisibility();
  88244. if (this._interactionsEnabled) {
  88245. this._scene.unregisterBeforeRender(this.beforeRender);
  88246. }
  88247. // resize to update width and height when exiting vr exits fullscreen
  88248. this._scene.getEngine().resize();
  88249. };
  88250. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  88251. /**
  88252. * The position of the vr experience helper.
  88253. */
  88254. get: function () {
  88255. return this._position;
  88256. },
  88257. /**
  88258. * Sets the position of the vr experience helper.
  88259. */
  88260. set: function (value) {
  88261. this._position = value;
  88262. if (this._scene.activeCamera) {
  88263. this._scene.activeCamera.position = value;
  88264. }
  88265. },
  88266. enumerable: true,
  88267. configurable: true
  88268. });
  88269. /**
  88270. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  88271. */
  88272. VRExperienceHelper.prototype.enableInteractions = function () {
  88273. var _this = this;
  88274. if (!this._interactionsEnabled) {
  88275. this._interactionsRequested = true;
  88276. if (this.leftController) {
  88277. this._enableInteractionOnController(this.leftController);
  88278. }
  88279. if (this.rightController) {
  88280. this._enableInteractionOnController(this.rightController);
  88281. }
  88282. this.raySelectionPredicate = function (mesh) {
  88283. return mesh.isVisible;
  88284. };
  88285. this.meshSelectionPredicate = function (mesh) {
  88286. return true;
  88287. };
  88288. this._raySelectionPredicate = function (mesh) {
  88289. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  88290. && mesh.name.indexOf("teleportationTarget") === -1
  88291. && mesh.name.indexOf("torusTeleportation") === -1
  88292. && mesh.name.indexOf("laserPointer") === -1)) {
  88293. return _this.raySelectionPredicate(mesh);
  88294. }
  88295. return false;
  88296. };
  88297. this._interactionsEnabled = true;
  88298. }
  88299. };
  88300. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  88301. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  88302. if (this._floorMeshesCollection[i].id === mesh.id) {
  88303. return true;
  88304. }
  88305. }
  88306. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  88307. return true;
  88308. }
  88309. return false;
  88310. };
  88311. /**
  88312. * Adds a floor mesh to be used for teleportation.
  88313. * @param floorMesh the mesh to be used for teleportation.
  88314. */
  88315. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  88316. if (!this._floorMeshesCollection) {
  88317. return;
  88318. }
  88319. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  88320. return;
  88321. }
  88322. this._floorMeshesCollection.push(floorMesh);
  88323. };
  88324. /**
  88325. * Removes a floor mesh from being used for teleportation.
  88326. * @param floorMesh the mesh to be removed.
  88327. */
  88328. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  88329. if (!this._floorMeshesCollection) {
  88330. return;
  88331. }
  88332. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  88333. if (meshIndex !== -1) {
  88334. this._floorMeshesCollection.splice(meshIndex, 1);
  88335. }
  88336. };
  88337. /**
  88338. * Enables interactions and teleportation using the VR controllers and gaze.
  88339. * @param vrTeleportationOptions options to modify teleportation behavior.
  88340. */
  88341. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  88342. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  88343. if (!this._teleportationInitialized) {
  88344. this._teleportationRequested = true;
  88345. this.enableInteractions();
  88346. if (vrTeleportationOptions.floorMeshName) {
  88347. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  88348. }
  88349. if (vrTeleportationOptions.floorMeshes) {
  88350. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  88351. }
  88352. if (this.leftController != null) {
  88353. this._enableTeleportationOnController(this.leftController);
  88354. }
  88355. if (this.rightController != null) {
  88356. this._enableTeleportationOnController(this.rightController);
  88357. }
  88358. // Creates an image processing post process for the vignette not relying
  88359. // on the main scene configuration for image processing to reduce setup and spaces
  88360. // (gamma/linear) conflicts.
  88361. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  88362. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  88363. imageProcessingConfiguration.vignetteEnabled = true;
  88364. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  88365. this._webVRCamera.detachPostProcess(this._postProcessMove);
  88366. this._teleportationInitialized = true;
  88367. if (this._isDefaultTeleportationTarget) {
  88368. this._createTeleportationCircles();
  88369. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  88370. }
  88371. }
  88372. };
  88373. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  88374. var _this = this;
  88375. var controllerMesh = controller.webVRController.mesh;
  88376. if (controllerMesh) {
  88377. controller._interactionsEnabled = true;
  88378. controller._activatePointer();
  88379. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  88380. // Enabling / disabling laserPointer
  88381. if (_this._displayLaserPointer && stateObject.value === 1) {
  88382. if (controller._activePointer) {
  88383. controller._deactivatePointer();
  88384. }
  88385. else {
  88386. controller._activatePointer();
  88387. }
  88388. if (_this.displayGaze) {
  88389. controller._gazeTracker.isVisible = controller._activePointer;
  88390. }
  88391. }
  88392. });
  88393. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  88394. if (!controller._pointerDownOnMeshAsked) {
  88395. if (stateObject.value > _this._padSensibilityUp) {
  88396. controller._selectionPointerDown();
  88397. }
  88398. }
  88399. else if (stateObject.value < _this._padSensibilityDown) {
  88400. controller._selectionPointerUp();
  88401. }
  88402. });
  88403. }
  88404. };
  88405. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  88406. // Dont teleport if another gaze already requested teleportation
  88407. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  88408. return;
  88409. }
  88410. if (!gazer._teleportationRequestInitiated) {
  88411. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  88412. gazer._activatePointer();
  88413. gazer._teleportationRequestInitiated = true;
  88414. }
  88415. }
  88416. else {
  88417. // Listening to the proper controller values changes to confirm teleportation
  88418. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  88419. if (this._teleportActive) {
  88420. this._teleportCamera(this._haloCenter);
  88421. }
  88422. gazer._teleportationRequestInitiated = false;
  88423. }
  88424. }
  88425. };
  88426. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  88427. // Only rotate when user is not currently selecting a teleportation location
  88428. if (gazer._teleportationRequestInitiated) {
  88429. return;
  88430. }
  88431. if (!gazer._rotationLeftAsked) {
  88432. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  88433. gazer._rotationLeftAsked = true;
  88434. if (this._rotationAllowed) {
  88435. this._rotateCamera(false);
  88436. }
  88437. }
  88438. }
  88439. else {
  88440. if (stateObject.x > -this._padSensibilityDown) {
  88441. gazer._rotationLeftAsked = false;
  88442. }
  88443. }
  88444. if (!gazer._rotationRightAsked) {
  88445. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  88446. gazer._rotationRightAsked = true;
  88447. if (this._rotationAllowed) {
  88448. this._rotateCamera(true);
  88449. }
  88450. }
  88451. }
  88452. else {
  88453. if (stateObject.x < this._padSensibilityDown) {
  88454. gazer._rotationRightAsked = false;
  88455. }
  88456. }
  88457. };
  88458. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  88459. // Only teleport backwards when user is not currently selecting a teleportation location
  88460. if (gazer._teleportationRequestInitiated) {
  88461. return;
  88462. }
  88463. // Teleport backwards
  88464. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  88465. if (!gazer._teleportationBackRequestInitiated) {
  88466. if (!this.currentVRCamera) {
  88467. return;
  88468. }
  88469. // Get rotation and position of the current camera
  88470. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  88471. var position = this.currentVRCamera.position;
  88472. // If the camera has device position, use that instead
  88473. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  88474. rotation = this.currentVRCamera.deviceRotationQuaternion;
  88475. position = this.currentVRCamera.devicePosition;
  88476. }
  88477. // Get matrix with only the y rotation of the device rotation
  88478. rotation.toEulerAnglesToRef(this._workingVector);
  88479. this._workingVector.z = 0;
  88480. this._workingVector.x = 0;
  88481. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  88482. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  88483. // Rotate backwards ray by device rotation to cast at the ground behind the user
  88484. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  88485. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  88486. var ray = new BABYLON.Ray(position, this._workingVector);
  88487. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  88488. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  88489. this._teleportCamera(hit.pickedPoint);
  88490. }
  88491. gazer._teleportationBackRequestInitiated = true;
  88492. }
  88493. }
  88494. else {
  88495. gazer._teleportationBackRequestInitiated = false;
  88496. }
  88497. };
  88498. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  88499. var _this = this;
  88500. var controllerMesh = controller.webVRController.mesh;
  88501. if (controllerMesh) {
  88502. if (!controller._interactionsEnabled) {
  88503. this._enableInteractionOnController(controller);
  88504. }
  88505. controller._interactionsEnabled = true;
  88506. controller._teleportationEnabled = true;
  88507. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  88508. controller._dpadPressed = false;
  88509. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  88510. controller._dpadPressed = stateObject.pressed;
  88511. if (!controller._dpadPressed) {
  88512. controller._rotationLeftAsked = false;
  88513. controller._rotationRightAsked = false;
  88514. controller._teleportationBackRequestInitiated = false;
  88515. }
  88516. });
  88517. }
  88518. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  88519. if (_this.teleportationEnabled) {
  88520. _this._checkTeleportBackwards(stateObject, controller);
  88521. _this._checkTeleportWithRay(stateObject, controller);
  88522. }
  88523. _this._checkRotate(stateObject, controller);
  88524. });
  88525. }
  88526. };
  88527. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  88528. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  88529. this._teleportationTarget.isPickable = false;
  88530. var length = 512;
  88531. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  88532. dynamicTexture.hasAlpha = true;
  88533. var context = dynamicTexture.getContext();
  88534. var centerX = length / 2;
  88535. var centerY = length / 2;
  88536. var radius = 200;
  88537. context.beginPath();
  88538. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  88539. context.fillStyle = this._teleportationFillColor;
  88540. context.fill();
  88541. context.lineWidth = 10;
  88542. context.strokeStyle = this._teleportationBorderColor;
  88543. context.stroke();
  88544. context.closePath();
  88545. dynamicTexture.update();
  88546. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  88547. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  88548. this._teleportationTarget.material = teleportationCircleMaterial;
  88549. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  88550. torus.isPickable = false;
  88551. torus.parent = this._teleportationTarget;
  88552. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  88553. var keys = [];
  88554. keys.push({
  88555. frame: 0,
  88556. value: 0
  88557. });
  88558. keys.push({
  88559. frame: 30,
  88560. value: 0.4
  88561. });
  88562. keys.push({
  88563. frame: 60,
  88564. value: 0
  88565. });
  88566. animationInnerCircle.setKeys(keys);
  88567. var easingFunction = new BABYLON.SineEase();
  88568. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  88569. animationInnerCircle.setEasingFunction(easingFunction);
  88570. torus.animations = [];
  88571. torus.animations.push(animationInnerCircle);
  88572. this._scene.beginAnimation(torus, 0, 60, true);
  88573. this._hideTeleportationTarget();
  88574. };
  88575. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  88576. this._teleportActive = true;
  88577. if (this._teleportationInitialized) {
  88578. this._teleportationTarget.isVisible = true;
  88579. if (this._isDefaultTeleportationTarget) {
  88580. this._teleportationTarget.getChildren()[0].isVisible = true;
  88581. }
  88582. }
  88583. };
  88584. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  88585. this._teleportActive = false;
  88586. if (this._teleportationInitialized) {
  88587. this._teleportationTarget.isVisible = false;
  88588. if (this._isDefaultTeleportationTarget) {
  88589. this._teleportationTarget.getChildren()[0].isVisible = false;
  88590. }
  88591. }
  88592. };
  88593. VRExperienceHelper.prototype._rotateCamera = function (right) {
  88594. var _this = this;
  88595. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  88596. return;
  88597. }
  88598. if (right) {
  88599. this._rotationAngle++;
  88600. }
  88601. else {
  88602. this._rotationAngle--;
  88603. }
  88604. this.currentVRCamera.animations = [];
  88605. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  88606. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88607. var animationRotationKeys = [];
  88608. animationRotationKeys.push({
  88609. frame: 0,
  88610. value: this.currentVRCamera.rotationQuaternion
  88611. });
  88612. animationRotationKeys.push({
  88613. frame: 6,
  88614. value: target
  88615. });
  88616. animationRotation.setKeys(animationRotationKeys);
  88617. animationRotation.setEasingFunction(this._circleEase);
  88618. this.currentVRCamera.animations.push(animationRotation);
  88619. this._postProcessMove.animations = [];
  88620. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88621. var vignetteWeightKeys = [];
  88622. vignetteWeightKeys.push({
  88623. frame: 0,
  88624. value: 0
  88625. });
  88626. vignetteWeightKeys.push({
  88627. frame: 3,
  88628. value: 4
  88629. });
  88630. vignetteWeightKeys.push({
  88631. frame: 6,
  88632. value: 0
  88633. });
  88634. animationPP.setKeys(vignetteWeightKeys);
  88635. animationPP.setEasingFunction(this._circleEase);
  88636. this._postProcessMove.animations.push(animationPP);
  88637. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88638. var vignetteStretchKeys = [];
  88639. vignetteStretchKeys.push({
  88640. frame: 0,
  88641. value: 0
  88642. });
  88643. vignetteStretchKeys.push({
  88644. frame: 3,
  88645. value: 10
  88646. });
  88647. vignetteStretchKeys.push({
  88648. frame: 6,
  88649. value: 0
  88650. });
  88651. animationPP2.setKeys(vignetteStretchKeys);
  88652. animationPP2.setEasingFunction(this._circleEase);
  88653. this._postProcessMove.animations.push(animationPP2);
  88654. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  88655. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  88656. this._postProcessMove.samples = 4;
  88657. this._webVRCamera.attachPostProcess(this._postProcessMove);
  88658. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  88659. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  88660. });
  88661. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  88662. };
  88663. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  88664. if (hit.pickedPoint) {
  88665. if (gazer._teleportationRequestInitiated) {
  88666. this._displayTeleportationTarget();
  88667. this._haloCenter.copyFrom(hit.pickedPoint);
  88668. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  88669. }
  88670. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  88671. if (pickNormal) {
  88672. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  88673. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  88674. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  88675. }
  88676. this._teleportationTarget.position.y += 0.1;
  88677. }
  88678. };
  88679. VRExperienceHelper.prototype._teleportCamera = function (location) {
  88680. var _this = this;
  88681. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  88682. return;
  88683. }
  88684. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  88685. // offset of the headset from the anchor.
  88686. if (this.webVRCamera.leftCamera) {
  88687. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  88688. this._workingVector.subtractInPlace(this.webVRCamera.position);
  88689. location.subtractToRef(this._workingVector, this._workingVector);
  88690. }
  88691. else {
  88692. this._workingVector.copyFrom(location);
  88693. }
  88694. // Add height to account for user's height offset
  88695. if (this.isInVRMode) {
  88696. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  88697. }
  88698. else {
  88699. this._workingVector.y += this._defaultHeight;
  88700. }
  88701. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  88702. // Create animation from the camera's position to the new location
  88703. this.currentVRCamera.animations = [];
  88704. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88705. var animationCameraTeleportationKeys = [{
  88706. frame: 0,
  88707. value: this.currentVRCamera.position
  88708. },
  88709. {
  88710. frame: 11,
  88711. value: this._workingVector
  88712. }
  88713. ];
  88714. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  88715. animationCameraTeleportation.setEasingFunction(this._circleEase);
  88716. this.currentVRCamera.animations.push(animationCameraTeleportation);
  88717. this._postProcessMove.animations = [];
  88718. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88719. var vignetteWeightKeys = [];
  88720. vignetteWeightKeys.push({
  88721. frame: 0,
  88722. value: 0
  88723. });
  88724. vignetteWeightKeys.push({
  88725. frame: 5,
  88726. value: 8
  88727. });
  88728. vignetteWeightKeys.push({
  88729. frame: 11,
  88730. value: 0
  88731. });
  88732. animationPP.setKeys(vignetteWeightKeys);
  88733. this._postProcessMove.animations.push(animationPP);
  88734. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88735. var vignetteStretchKeys = [];
  88736. vignetteStretchKeys.push({
  88737. frame: 0,
  88738. value: 0
  88739. });
  88740. vignetteStretchKeys.push({
  88741. frame: 5,
  88742. value: 10
  88743. });
  88744. vignetteStretchKeys.push({
  88745. frame: 11,
  88746. value: 0
  88747. });
  88748. animationPP2.setKeys(vignetteStretchKeys);
  88749. this._postProcessMove.animations.push(animationPP2);
  88750. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  88751. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  88752. this._webVRCamera.attachPostProcess(this._postProcessMove);
  88753. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  88754. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  88755. });
  88756. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  88757. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  88758. });
  88759. this._hideTeleportationTarget();
  88760. };
  88761. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  88762. if (normal) {
  88763. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  88764. if (angle < Math.PI / 2) {
  88765. normal.scaleInPlace(-1);
  88766. }
  88767. }
  88768. return normal;
  88769. };
  88770. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  88771. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  88772. return;
  88773. }
  88774. var ray = gazer._getForwardRay(this._rayLength);
  88775. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  88776. // Moving the gazeTracker on the mesh face targetted
  88777. if (hit && hit.pickedPoint) {
  88778. if (this._displayGaze) {
  88779. var multiplier = 1;
  88780. gazer._gazeTracker.isVisible = true;
  88781. if (gazer._isActionableMesh) {
  88782. multiplier = 3;
  88783. }
  88784. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  88785. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  88786. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  88787. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  88788. // To avoid z-fighting
  88789. var deltaFighting = 0.002;
  88790. if (pickNormal) {
  88791. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  88792. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  88793. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  88794. }
  88795. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  88796. if (gazer._gazeTracker.position.x < 0) {
  88797. gazer._gazeTracker.position.x += deltaFighting;
  88798. }
  88799. else {
  88800. gazer._gazeTracker.position.x -= deltaFighting;
  88801. }
  88802. if (gazer._gazeTracker.position.y < 0) {
  88803. gazer._gazeTracker.position.y += deltaFighting;
  88804. }
  88805. else {
  88806. gazer._gazeTracker.position.y -= deltaFighting;
  88807. }
  88808. if (gazer._gazeTracker.position.z < 0) {
  88809. gazer._gazeTracker.position.z += deltaFighting;
  88810. }
  88811. else {
  88812. gazer._gazeTracker.position.z -= deltaFighting;
  88813. }
  88814. }
  88815. // Changing the size of the laser pointer based on the distance from the targetted point
  88816. gazer._updatePointerDistance(hit.distance);
  88817. }
  88818. else {
  88819. gazer._updatePointerDistance();
  88820. gazer._gazeTracker.isVisible = false;
  88821. }
  88822. if (hit && hit.pickedMesh) {
  88823. gazer._currentHit = hit;
  88824. if (gazer._pointerDownOnMeshAsked) {
  88825. this._scene.simulatePointerMove(gazer._currentHit, { pointerId: gazer._id });
  88826. }
  88827. // The object selected is the floor, we're in a teleportation scenario
  88828. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  88829. // Moving the teleportation area to this targetted point
  88830. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  88831. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  88832. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  88833. }
  88834. gazer._currentMeshSelected = null;
  88835. if (gazer._teleportationRequestInitiated) {
  88836. this._moveTeleportationSelectorTo(hit, gazer, ray);
  88837. }
  88838. return;
  88839. }
  88840. // If not, we're in a selection scenario
  88841. //this._teleportationAllowed = false;
  88842. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  88843. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  88844. this.onNewMeshPicked.notifyObservers(hit);
  88845. gazer._currentMeshSelected = hit.pickedMesh;
  88846. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  88847. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  88848. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  88849. gazer._isActionableMesh = true;
  88850. }
  88851. else {
  88852. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88853. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88854. gazer._isActionableMesh = false;
  88855. }
  88856. try {
  88857. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  88858. }
  88859. catch (err) {
  88860. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  88861. }
  88862. }
  88863. else {
  88864. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  88865. gazer._currentMeshSelected = null;
  88866. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88867. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88868. }
  88869. }
  88870. }
  88871. else {
  88872. gazer._currentHit = null;
  88873. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  88874. gazer._currentMeshSelected = null;
  88875. //this._teleportationAllowed = false;
  88876. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88877. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88878. }
  88879. };
  88880. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  88881. if (mesh) {
  88882. this.onSelectedMeshUnselected.notifyObservers(mesh);
  88883. }
  88884. };
  88885. /**
  88886. * Sets the color of the laser ray from the vr controllers.
  88887. * @param color new color for the ray.
  88888. */
  88889. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  88890. if (this.leftController) {
  88891. this.leftController._setLaserPointerColor(color);
  88892. }
  88893. if (this.rightController) {
  88894. this.rightController._setLaserPointerColor(color);
  88895. }
  88896. };
  88897. /**
  88898. * Sets the color of the ray from the vr headsets gaze.
  88899. * @param color new color for the ray.
  88900. */
  88901. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  88902. if (!this._cameraGazer._gazeTracker.material) {
  88903. return;
  88904. }
  88905. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  88906. if (this.leftController) {
  88907. this.leftController._gazeTracker.material.emissiveColor = color;
  88908. }
  88909. if (this.rightController) {
  88910. this.rightController._gazeTracker.material.emissiveColor = color;
  88911. }
  88912. };
  88913. /**
  88914. * Exits VR and disposes of the vr experience helper
  88915. */
  88916. VRExperienceHelper.prototype.dispose = function () {
  88917. if (this.isInVRMode) {
  88918. this.exitVR();
  88919. }
  88920. if (this._postProcessMove) {
  88921. this._postProcessMove.dispose();
  88922. }
  88923. if (this._webVRCamera) {
  88924. this._webVRCamera.dispose();
  88925. }
  88926. if (this._vrDeviceOrientationCamera) {
  88927. this._vrDeviceOrientationCamera.dispose();
  88928. }
  88929. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  88930. document.body.removeChild(this._btnVR);
  88931. }
  88932. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  88933. this._deviceOrientationCamera.dispose();
  88934. }
  88935. if (this._cameraGazer) {
  88936. this._cameraGazer.dispose();
  88937. }
  88938. if (this.leftController) {
  88939. this.leftController.dispose();
  88940. }
  88941. if (this.rightController) {
  88942. this.rightController.dispose();
  88943. }
  88944. if (this._teleportationTarget) {
  88945. this._teleportationTarget.dispose();
  88946. }
  88947. this._floorMeshesCollection = [];
  88948. document.removeEventListener("keydown", this._onKeyDown);
  88949. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  88950. window.removeEventListener("resize", this._onResize);
  88951. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  88952. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  88953. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  88954. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  88955. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  88956. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  88957. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  88958. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  88959. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  88960. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  88961. this._scene.unregisterBeforeRender(this.beforeRender);
  88962. };
  88963. /**
  88964. * Gets the name of the VRExperienceHelper class
  88965. * @returns "VRExperienceHelper"
  88966. */
  88967. VRExperienceHelper.prototype.getClassName = function () {
  88968. return "VRExperienceHelper";
  88969. };
  88970. return VRExperienceHelper;
  88971. }());
  88972. BABYLON.VRExperienceHelper = VRExperienceHelper;
  88973. })(BABYLON || (BABYLON = {}));
  88974. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  88975. // Mainly based on these 2 articles :
  88976. // 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
  88977. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  88978. var BABYLON;
  88979. (function (BABYLON) {
  88980. /**
  88981. * Defines the potential axis of a Joystick
  88982. */
  88983. var JoystickAxis;
  88984. (function (JoystickAxis) {
  88985. /** X axis */
  88986. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  88987. /** Y axis */
  88988. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  88989. /** Z axis */
  88990. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  88991. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  88992. /**
  88993. * Class used to define virtual joystick (used in touch mode)
  88994. */
  88995. var VirtualJoystick = /** @class */ (function () {
  88996. /**
  88997. * Creates a new virtual joystick
  88998. * @param leftJoystick defines that the joystick is for left hand (false by default)
  88999. */
  89000. function VirtualJoystick(leftJoystick) {
  89001. var _this = this;
  89002. if (leftJoystick) {
  89003. this._leftJoystick = true;
  89004. }
  89005. else {
  89006. this._leftJoystick = false;
  89007. }
  89008. VirtualJoystick._globalJoystickIndex++;
  89009. // By default left & right arrow keys are moving the X
  89010. // and up & down keys are moving the Y
  89011. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  89012. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  89013. this.reverseLeftRight = false;
  89014. this.reverseUpDown = false;
  89015. // collections of pointers
  89016. this._touches = new BABYLON.StringDictionary();
  89017. this.deltaPosition = BABYLON.Vector3.Zero();
  89018. this._joystickSensibility = 25;
  89019. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  89020. this._onResize = function (evt) {
  89021. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  89022. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  89023. if (VirtualJoystick.vjCanvas) {
  89024. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  89025. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  89026. }
  89027. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  89028. };
  89029. // injecting a canvas element on top of the canvas 3D game
  89030. if (!VirtualJoystick.vjCanvas) {
  89031. window.addEventListener("resize", this._onResize, false);
  89032. VirtualJoystick.vjCanvas = document.createElement("canvas");
  89033. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  89034. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  89035. VirtualJoystick.vjCanvas.width = window.innerWidth;
  89036. VirtualJoystick.vjCanvas.height = window.innerHeight;
  89037. VirtualJoystick.vjCanvas.style.width = "100%";
  89038. VirtualJoystick.vjCanvas.style.height = "100%";
  89039. VirtualJoystick.vjCanvas.style.position = "absolute";
  89040. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  89041. VirtualJoystick.vjCanvas.style.top = "0px";
  89042. VirtualJoystick.vjCanvas.style.left = "0px";
  89043. VirtualJoystick.vjCanvas.style.zIndex = "5";
  89044. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  89045. // Support for jQuery PEP polyfill
  89046. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  89047. var context = VirtualJoystick.vjCanvas.getContext('2d');
  89048. if (!context) {
  89049. throw new Error("Unable to create canvas for virtual joystick");
  89050. }
  89051. VirtualJoystick.vjCanvasContext = context;
  89052. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  89053. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  89054. document.body.appendChild(VirtualJoystick.vjCanvas);
  89055. }
  89056. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  89057. this.pressed = false;
  89058. // default joystick color
  89059. this._joystickColor = "cyan";
  89060. this._joystickPointerID = -1;
  89061. // current joystick position
  89062. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  89063. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  89064. // origin joystick position
  89065. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  89066. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  89067. this._onPointerDownHandlerRef = function (evt) {
  89068. _this._onPointerDown(evt);
  89069. };
  89070. this._onPointerMoveHandlerRef = function (evt) {
  89071. _this._onPointerMove(evt);
  89072. };
  89073. this._onPointerUpHandlerRef = function (evt) {
  89074. _this._onPointerUp(evt);
  89075. };
  89076. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  89077. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  89078. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  89079. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  89080. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  89081. evt.preventDefault(); // Disables system menu
  89082. }, false);
  89083. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  89084. }
  89085. /**
  89086. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  89087. * @param newJoystickSensibility defines the new sensibility
  89088. */
  89089. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  89090. this._joystickSensibility = newJoystickSensibility;
  89091. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  89092. };
  89093. VirtualJoystick.prototype._onPointerDown = function (e) {
  89094. var positionOnScreenCondition;
  89095. e.preventDefault();
  89096. if (this._leftJoystick === true) {
  89097. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  89098. }
  89099. else {
  89100. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  89101. }
  89102. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  89103. // First contact will be dedicated to the virtual joystick
  89104. this._joystickPointerID = e.pointerId;
  89105. this._joystickPointerStartPos.x = e.clientX;
  89106. this._joystickPointerStartPos.y = e.clientY;
  89107. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  89108. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  89109. this._deltaJoystickVector.x = 0;
  89110. this._deltaJoystickVector.y = 0;
  89111. this.pressed = true;
  89112. this._touches.add(e.pointerId.toString(), e);
  89113. }
  89114. else {
  89115. // You can only trigger the action buttons with a joystick declared
  89116. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  89117. this._action();
  89118. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  89119. }
  89120. }
  89121. };
  89122. VirtualJoystick.prototype._onPointerMove = function (e) {
  89123. // If the current pointer is the one associated to the joystick (first touch contact)
  89124. if (this._joystickPointerID == e.pointerId) {
  89125. this._joystickPointerPos.x = e.clientX;
  89126. this._joystickPointerPos.y = e.clientY;
  89127. this._deltaJoystickVector = this._joystickPointerPos.clone();
  89128. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  89129. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  89130. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  89131. switch (this._axisTargetedByLeftAndRight) {
  89132. case JoystickAxis.X:
  89133. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  89134. break;
  89135. case JoystickAxis.Y:
  89136. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  89137. break;
  89138. case JoystickAxis.Z:
  89139. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  89140. break;
  89141. }
  89142. var directionUpDown = this.reverseUpDown ? 1 : -1;
  89143. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  89144. switch (this._axisTargetedByUpAndDown) {
  89145. case JoystickAxis.X:
  89146. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  89147. break;
  89148. case JoystickAxis.Y:
  89149. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  89150. break;
  89151. case JoystickAxis.Z:
  89152. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  89153. break;
  89154. }
  89155. }
  89156. else {
  89157. var data = this._touches.get(e.pointerId.toString());
  89158. if (data) {
  89159. data.x = e.clientX;
  89160. data.y = e.clientY;
  89161. }
  89162. }
  89163. };
  89164. VirtualJoystick.prototype._onPointerUp = function (e) {
  89165. if (this._joystickPointerID == e.pointerId) {
  89166. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  89167. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  89168. this._joystickPointerID = -1;
  89169. this.pressed = false;
  89170. }
  89171. else {
  89172. var touch = this._touches.get(e.pointerId.toString());
  89173. if (touch) {
  89174. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  89175. }
  89176. }
  89177. this._deltaJoystickVector.x = 0;
  89178. this._deltaJoystickVector.y = 0;
  89179. this._touches.remove(e.pointerId.toString());
  89180. };
  89181. /**
  89182. * Change the color of the virtual joystick
  89183. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  89184. */
  89185. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  89186. this._joystickColor = newColor;
  89187. };
  89188. /**
  89189. * Defines a callback to call when the joystick is touched
  89190. * @param action defines the callback
  89191. */
  89192. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  89193. this._action = action;
  89194. };
  89195. /**
  89196. * Defines which axis you'd like to control for left & right
  89197. * @param axis defines the axis to use
  89198. */
  89199. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  89200. switch (axis) {
  89201. case JoystickAxis.X:
  89202. case JoystickAxis.Y:
  89203. case JoystickAxis.Z:
  89204. this._axisTargetedByLeftAndRight = axis;
  89205. break;
  89206. default:
  89207. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  89208. break;
  89209. }
  89210. };
  89211. /**
  89212. * Defines which axis you'd like to control for up & down
  89213. * @param axis defines the axis to use
  89214. */
  89215. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  89216. switch (axis) {
  89217. case JoystickAxis.X:
  89218. case JoystickAxis.Y:
  89219. case JoystickAxis.Z:
  89220. this._axisTargetedByUpAndDown = axis;
  89221. break;
  89222. default:
  89223. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  89224. break;
  89225. }
  89226. };
  89227. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  89228. var _this = this;
  89229. if (this.pressed) {
  89230. this._touches.forEach(function (key, touch) {
  89231. if (touch.pointerId === _this._joystickPointerID) {
  89232. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  89233. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  89234. VirtualJoystick.vjCanvasContext.beginPath();
  89235. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  89236. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  89237. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  89238. VirtualJoystick.vjCanvasContext.stroke();
  89239. VirtualJoystick.vjCanvasContext.closePath();
  89240. VirtualJoystick.vjCanvasContext.beginPath();
  89241. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  89242. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  89243. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  89244. VirtualJoystick.vjCanvasContext.stroke();
  89245. VirtualJoystick.vjCanvasContext.closePath();
  89246. VirtualJoystick.vjCanvasContext.beginPath();
  89247. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  89248. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  89249. VirtualJoystick.vjCanvasContext.stroke();
  89250. VirtualJoystick.vjCanvasContext.closePath();
  89251. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  89252. }
  89253. else {
  89254. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  89255. VirtualJoystick.vjCanvasContext.beginPath();
  89256. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  89257. VirtualJoystick.vjCanvasContext.beginPath();
  89258. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  89259. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  89260. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  89261. VirtualJoystick.vjCanvasContext.stroke();
  89262. VirtualJoystick.vjCanvasContext.closePath();
  89263. touch.prevX = touch.x;
  89264. touch.prevY = touch.y;
  89265. }
  89266. ;
  89267. });
  89268. }
  89269. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  89270. };
  89271. /**
  89272. * Release internal HTML canvas
  89273. */
  89274. VirtualJoystick.prototype.releaseCanvas = function () {
  89275. if (VirtualJoystick.vjCanvas) {
  89276. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  89277. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  89278. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  89279. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  89280. window.removeEventListener("resize", this._onResize);
  89281. document.body.removeChild(VirtualJoystick.vjCanvas);
  89282. VirtualJoystick.vjCanvas = null;
  89283. }
  89284. };
  89285. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  89286. VirtualJoystick._globalJoystickIndex = 0;
  89287. return VirtualJoystick;
  89288. }());
  89289. BABYLON.VirtualJoystick = VirtualJoystick;
  89290. })(BABYLON || (BABYLON = {}));
  89291. //# sourceMappingURL=babylon.virtualJoystick.js.map
  89292. var BABYLON;
  89293. (function (BABYLON) {
  89294. // We're mainly based on the logic defined into the FreeCamera code
  89295. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  89296. __extends(VirtualJoysticksCamera, _super);
  89297. function VirtualJoysticksCamera(name, position, scene) {
  89298. var _this = _super.call(this, name, position, scene) || this;
  89299. _this.inputs.addVirtualJoystick();
  89300. return _this;
  89301. }
  89302. VirtualJoysticksCamera.prototype.getClassName = function () {
  89303. return "VirtualJoysticksCamera";
  89304. };
  89305. return VirtualJoysticksCamera;
  89306. }(BABYLON.FreeCamera));
  89307. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  89308. })(BABYLON || (BABYLON = {}));
  89309. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  89310. var BABYLON;
  89311. (function (BABYLON) {
  89312. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  89313. function FreeCameraVirtualJoystickInput() {
  89314. }
  89315. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  89316. return this._leftjoystick;
  89317. };
  89318. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  89319. return this._rightjoystick;
  89320. };
  89321. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  89322. if (this._leftjoystick) {
  89323. var camera = this.camera;
  89324. var speed = camera._computeLocalCameraSpeed() * 50;
  89325. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  89326. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  89327. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  89328. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  89329. if (!this._leftjoystick.pressed) {
  89330. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  89331. }
  89332. if (!this._rightjoystick.pressed) {
  89333. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  89334. }
  89335. }
  89336. };
  89337. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  89338. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  89339. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  89340. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  89341. this._leftjoystick.setJoystickSensibility(0.15);
  89342. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  89343. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  89344. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  89345. this._rightjoystick.reverseUpDown = true;
  89346. this._rightjoystick.setJoystickSensibility(0.05);
  89347. this._rightjoystick.setJoystickColor("yellow");
  89348. };
  89349. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  89350. this._leftjoystick.releaseCanvas();
  89351. this._rightjoystick.releaseCanvas();
  89352. };
  89353. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  89354. return "FreeCameraVirtualJoystickInput";
  89355. };
  89356. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  89357. return "virtualJoystick";
  89358. };
  89359. return FreeCameraVirtualJoystickInput;
  89360. }());
  89361. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  89362. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  89363. })(BABYLON || (BABYLON = {}));
  89364. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  89365. var BABYLON;
  89366. (function (BABYLON) {
  89367. var SimplificationSettings = /** @class */ (function () {
  89368. function SimplificationSettings(quality, distance, optimizeMesh) {
  89369. this.quality = quality;
  89370. this.distance = distance;
  89371. this.optimizeMesh = optimizeMesh;
  89372. }
  89373. return SimplificationSettings;
  89374. }());
  89375. BABYLON.SimplificationSettings = SimplificationSettings;
  89376. var SimplificationQueue = /** @class */ (function () {
  89377. function SimplificationQueue() {
  89378. this.running = false;
  89379. this._simplificationArray = [];
  89380. }
  89381. SimplificationQueue.prototype.addTask = function (task) {
  89382. this._simplificationArray.push(task);
  89383. };
  89384. SimplificationQueue.prototype.executeNext = function () {
  89385. var task = this._simplificationArray.pop();
  89386. if (task) {
  89387. this.running = true;
  89388. this.runSimplification(task);
  89389. }
  89390. else {
  89391. this.running = false;
  89392. }
  89393. };
  89394. SimplificationQueue.prototype.runSimplification = function (task) {
  89395. var _this = this;
  89396. if (task.parallelProcessing) {
  89397. //parallel simplifier
  89398. task.settings.forEach(function (setting) {
  89399. var simplifier = _this.getSimplifier(task);
  89400. simplifier.simplify(setting, function (newMesh) {
  89401. task.mesh.addLODLevel(setting.distance, newMesh);
  89402. newMesh.isVisible = true;
  89403. //check if it is the last
  89404. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  89405. //all done, run the success callback.
  89406. task.successCallback();
  89407. }
  89408. _this.executeNext();
  89409. });
  89410. });
  89411. }
  89412. else {
  89413. //single simplifier.
  89414. var simplifier = this.getSimplifier(task);
  89415. var runDecimation = function (setting, callback) {
  89416. simplifier.simplify(setting, function (newMesh) {
  89417. task.mesh.addLODLevel(setting.distance, newMesh);
  89418. newMesh.isVisible = true;
  89419. //run the next quality level
  89420. callback();
  89421. });
  89422. };
  89423. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  89424. runDecimation(task.settings[loop.index], function () {
  89425. loop.executeNext();
  89426. });
  89427. }, function () {
  89428. //execution ended, run the success callback.
  89429. if (task.successCallback) {
  89430. task.successCallback();
  89431. }
  89432. _this.executeNext();
  89433. });
  89434. }
  89435. };
  89436. SimplificationQueue.prototype.getSimplifier = function (task) {
  89437. switch (task.simplificationType) {
  89438. case SimplificationType.QUADRATIC:
  89439. default:
  89440. return new QuadraticErrorSimplification(task.mesh);
  89441. }
  89442. };
  89443. return SimplificationQueue;
  89444. }());
  89445. BABYLON.SimplificationQueue = SimplificationQueue;
  89446. /**
  89447. * The implemented types of simplification
  89448. * At the moment only Quadratic Error Decimation is implemented
  89449. */
  89450. var SimplificationType;
  89451. (function (SimplificationType) {
  89452. /** Quadratic error decimation */
  89453. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  89454. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  89455. var DecimationTriangle = /** @class */ (function () {
  89456. function DecimationTriangle(vertices) {
  89457. this.vertices = vertices;
  89458. this.error = new Array(4);
  89459. this.deleted = false;
  89460. this.isDirty = false;
  89461. this.deletePending = false;
  89462. this.borderFactor = 0;
  89463. }
  89464. return DecimationTriangle;
  89465. }());
  89466. BABYLON.DecimationTriangle = DecimationTriangle;
  89467. var DecimationVertex = /** @class */ (function () {
  89468. function DecimationVertex(position, id) {
  89469. this.position = position;
  89470. this.id = id;
  89471. this.isBorder = true;
  89472. this.q = new QuadraticMatrix();
  89473. this.triangleCount = 0;
  89474. this.triangleStart = 0;
  89475. this.originalOffsets = [];
  89476. }
  89477. DecimationVertex.prototype.updatePosition = function (newPosition) {
  89478. this.position.copyFrom(newPosition);
  89479. };
  89480. return DecimationVertex;
  89481. }());
  89482. BABYLON.DecimationVertex = DecimationVertex;
  89483. var QuadraticMatrix = /** @class */ (function () {
  89484. function QuadraticMatrix(data) {
  89485. this.data = new Array(10);
  89486. for (var i = 0; i < 10; ++i) {
  89487. if (data && data[i]) {
  89488. this.data[i] = data[i];
  89489. }
  89490. else {
  89491. this.data[i] = 0;
  89492. }
  89493. }
  89494. }
  89495. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  89496. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  89497. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  89498. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  89499. return det;
  89500. };
  89501. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  89502. for (var i = 0; i < 10; ++i) {
  89503. this.data[i] += matrix.data[i];
  89504. }
  89505. };
  89506. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  89507. for (var i = 0; i < 10; ++i) {
  89508. this.data[i] += data[i];
  89509. }
  89510. };
  89511. QuadraticMatrix.prototype.add = function (matrix) {
  89512. var m = new QuadraticMatrix();
  89513. for (var i = 0; i < 10; ++i) {
  89514. m.data[i] = this.data[i] + matrix.data[i];
  89515. }
  89516. return m;
  89517. };
  89518. QuadraticMatrix.FromData = function (a, b, c, d) {
  89519. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  89520. };
  89521. //returning an array to avoid garbage collection
  89522. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  89523. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  89524. };
  89525. return QuadraticMatrix;
  89526. }());
  89527. BABYLON.QuadraticMatrix = QuadraticMatrix;
  89528. var Reference = /** @class */ (function () {
  89529. function Reference(vertexId, triangleId) {
  89530. this.vertexId = vertexId;
  89531. this.triangleId = triangleId;
  89532. }
  89533. return Reference;
  89534. }());
  89535. BABYLON.Reference = Reference;
  89536. /**
  89537. * An implementation of the Quadratic Error simplification algorithm.
  89538. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  89539. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  89540. * @author RaananW
  89541. */
  89542. var QuadraticErrorSimplification = /** @class */ (function () {
  89543. function QuadraticErrorSimplification(_mesh) {
  89544. this._mesh = _mesh;
  89545. this.syncIterations = 5000;
  89546. this.aggressiveness = 7;
  89547. this.decimationIterations = 100;
  89548. this.boundingBoxEpsilon = BABYLON.Epsilon;
  89549. }
  89550. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  89551. var _this = this;
  89552. this.initDecimatedMesh();
  89553. //iterating through the submeshes array, one after the other.
  89554. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  89555. _this.initWithMesh(loop.index, function () {
  89556. _this.runDecimation(settings, loop.index, function () {
  89557. loop.executeNext();
  89558. });
  89559. }, settings.optimizeMesh);
  89560. }, function () {
  89561. setTimeout(function () {
  89562. successCallback(_this._reconstructedMesh);
  89563. }, 0);
  89564. });
  89565. };
  89566. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  89567. var _this = this;
  89568. var targetCount = ~~(this.triangles.length * settings.quality);
  89569. var deletedTriangles = 0;
  89570. var triangleCount = this.triangles.length;
  89571. var iterationFunction = function (iteration, callback) {
  89572. setTimeout(function () {
  89573. if (iteration % 5 === 0) {
  89574. _this.updateMesh(iteration === 0);
  89575. }
  89576. for (var i = 0; i < _this.triangles.length; ++i) {
  89577. _this.triangles[i].isDirty = false;
  89578. }
  89579. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  89580. var trianglesIterator = function (i) {
  89581. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  89582. var t = _this.triangles[tIdx];
  89583. if (!t)
  89584. return;
  89585. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  89586. return;
  89587. }
  89588. for (var j = 0; j < 3; ++j) {
  89589. if (t.error[j] < threshold) {
  89590. var deleted0 = [];
  89591. var deleted1 = [];
  89592. var v0 = t.vertices[j];
  89593. var v1 = t.vertices[(j + 1) % 3];
  89594. if (v0.isBorder || v1.isBorder)
  89595. continue;
  89596. var p = BABYLON.Vector3.Zero();
  89597. var n = BABYLON.Vector3.Zero();
  89598. var uv = BABYLON.Vector2.Zero();
  89599. var color = new BABYLON.Color4(0, 0, 0, 1);
  89600. _this.calculateError(v0, v1, p, n, uv, color);
  89601. var delTr = new Array();
  89602. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  89603. continue;
  89604. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  89605. continue;
  89606. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  89607. continue;
  89608. var uniqueArray = new Array();
  89609. delTr.forEach(function (deletedT) {
  89610. if (uniqueArray.indexOf(deletedT) === -1) {
  89611. deletedT.deletePending = true;
  89612. uniqueArray.push(deletedT);
  89613. }
  89614. });
  89615. if (uniqueArray.length % 2 !== 0) {
  89616. continue;
  89617. }
  89618. v0.q = v1.q.add(v0.q);
  89619. v0.updatePosition(p);
  89620. var tStart = _this.references.length;
  89621. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  89622. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  89623. var tCount = _this.references.length - tStart;
  89624. if (tCount <= v0.triangleCount) {
  89625. if (tCount) {
  89626. for (var c = 0; c < tCount; c++) {
  89627. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  89628. }
  89629. }
  89630. }
  89631. else {
  89632. v0.triangleStart = tStart;
  89633. }
  89634. v0.triangleCount = tCount;
  89635. break;
  89636. }
  89637. }
  89638. };
  89639. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  89640. }, 0);
  89641. };
  89642. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  89643. if (triangleCount - deletedTriangles <= targetCount)
  89644. loop.breakLoop();
  89645. else {
  89646. iterationFunction(loop.index, function () {
  89647. loop.executeNext();
  89648. });
  89649. }
  89650. }, function () {
  89651. setTimeout(function () {
  89652. //reconstruct this part of the mesh
  89653. _this.reconstructMesh(submeshIndex);
  89654. successCallback();
  89655. }, 0);
  89656. });
  89657. };
  89658. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  89659. var _this = this;
  89660. this.vertices = [];
  89661. this.triangles = [];
  89662. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  89663. var indices = this._mesh.getIndices();
  89664. var submesh = this._mesh.subMeshes[submeshIndex];
  89665. var findInVertices = function (positionToSearch) {
  89666. if (optimizeMesh) {
  89667. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  89668. if (_this.vertices[ii].position.equals(positionToSearch)) {
  89669. return _this.vertices[ii];
  89670. }
  89671. }
  89672. }
  89673. return null;
  89674. };
  89675. var vertexReferences = [];
  89676. var vertexInit = function (i) {
  89677. if (!positionData) {
  89678. return;
  89679. }
  89680. var offset = i + submesh.verticesStart;
  89681. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  89682. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  89683. vertex.originalOffsets.push(offset);
  89684. if (vertex.id === _this.vertices.length) {
  89685. _this.vertices.push(vertex);
  89686. }
  89687. vertexReferences.push(vertex.id);
  89688. };
  89689. //var totalVertices = mesh.getTotalVertices();
  89690. var totalVertices = submesh.verticesCount;
  89691. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  89692. var indicesInit = function (i) {
  89693. if (!indices) {
  89694. return;
  89695. }
  89696. var offset = (submesh.indexStart / 3) + i;
  89697. var pos = (offset * 3);
  89698. var i0 = indices[pos + 0];
  89699. var i1 = indices[pos + 1];
  89700. var i2 = indices[pos + 2];
  89701. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  89702. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  89703. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  89704. var triangle = new DecimationTriangle([v0, v1, v2]);
  89705. triangle.originalOffset = pos;
  89706. _this.triangles.push(triangle);
  89707. };
  89708. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  89709. _this.init(callback);
  89710. });
  89711. });
  89712. };
  89713. QuadraticErrorSimplification.prototype.init = function (callback) {
  89714. var _this = this;
  89715. var triangleInit1 = function (i) {
  89716. var t = _this.triangles[i];
  89717. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  89718. for (var j = 0; j < 3; j++) {
  89719. 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))));
  89720. }
  89721. };
  89722. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  89723. var triangleInit2 = function (i) {
  89724. var t = _this.triangles[i];
  89725. for (var j = 0; j < 3; ++j) {
  89726. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  89727. }
  89728. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  89729. };
  89730. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  89731. callback();
  89732. });
  89733. });
  89734. };
  89735. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  89736. var newTriangles = [];
  89737. var i;
  89738. for (i = 0; i < this.vertices.length; ++i) {
  89739. this.vertices[i].triangleCount = 0;
  89740. }
  89741. var t;
  89742. var j;
  89743. for (i = 0; i < this.triangles.length; ++i) {
  89744. if (!this.triangles[i].deleted) {
  89745. t = this.triangles[i];
  89746. for (j = 0; j < 3; ++j) {
  89747. t.vertices[j].triangleCount = 1;
  89748. }
  89749. newTriangles.push(t);
  89750. }
  89751. }
  89752. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  89753. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  89754. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  89755. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  89756. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  89757. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  89758. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  89759. var vertexCount = 0;
  89760. for (i = 0; i < this.vertices.length; ++i) {
  89761. var vertex = this.vertices[i];
  89762. vertex.id = vertexCount;
  89763. if (vertex.triangleCount) {
  89764. vertex.originalOffsets.forEach(function (originalOffset) {
  89765. if (!normalData) {
  89766. return;
  89767. }
  89768. newPositionData.push(vertex.position.x);
  89769. newPositionData.push(vertex.position.y);
  89770. newPositionData.push(vertex.position.z);
  89771. newNormalData.push(normalData[originalOffset * 3]);
  89772. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  89773. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  89774. if (uvs && uvs.length) {
  89775. newUVsData.push(uvs[(originalOffset * 2)]);
  89776. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  89777. }
  89778. else if (colorsData && colorsData.length) {
  89779. newColorsData.push(colorsData[(originalOffset * 4)]);
  89780. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  89781. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  89782. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  89783. }
  89784. ++vertexCount;
  89785. });
  89786. }
  89787. }
  89788. var startingIndex = this._reconstructedMesh.getTotalIndices();
  89789. var startingVertex = this._reconstructedMesh.getTotalVertices();
  89790. var submeshesArray = this._reconstructedMesh.subMeshes;
  89791. this._reconstructedMesh.subMeshes = [];
  89792. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  89793. var originalIndices = this._mesh.getIndices();
  89794. for (i = 0; i < newTriangles.length; ++i) {
  89795. t = newTriangles[i]; //now get the new referencing point for each vertex
  89796. [0, 1, 2].forEach(function (idx) {
  89797. var id = originalIndices[t.originalOffset + idx];
  89798. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  89799. if (offset < 0)
  89800. offset = 0;
  89801. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  89802. });
  89803. }
  89804. //overwriting the old vertex buffers and indices.
  89805. this._reconstructedMesh.setIndices(newIndicesArray);
  89806. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  89807. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  89808. if (newUVsData.length > 0)
  89809. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  89810. if (newColorsData.length > 0)
  89811. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  89812. //create submesh
  89813. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  89814. if (submeshIndex > 0) {
  89815. this._reconstructedMesh.subMeshes = [];
  89816. submeshesArray.forEach(function (submesh) {
  89817. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  89818. });
  89819. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  89820. }
  89821. };
  89822. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  89823. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  89824. this._reconstructedMesh.material = this._mesh.material;
  89825. this._reconstructedMesh.parent = this._mesh.parent;
  89826. this._reconstructedMesh.isVisible = false;
  89827. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  89828. };
  89829. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  89830. for (var i = 0; i < vertex1.triangleCount; ++i) {
  89831. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  89832. if (t.deleted)
  89833. continue;
  89834. var s = this.references[vertex1.triangleStart + i].vertexId;
  89835. var v1 = t.vertices[(s + 1) % 3];
  89836. var v2 = t.vertices[(s + 2) % 3];
  89837. if ((v1 === vertex2 || v2 === vertex2)) {
  89838. deletedArray[i] = true;
  89839. delTr.push(t);
  89840. continue;
  89841. }
  89842. var d1 = v1.position.subtract(point);
  89843. d1 = d1.normalize();
  89844. var d2 = v2.position.subtract(point);
  89845. d2 = d2.normalize();
  89846. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  89847. return true;
  89848. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  89849. deletedArray[i] = false;
  89850. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  89851. return true;
  89852. }
  89853. return false;
  89854. };
  89855. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  89856. var newDeleted = deletedTriangles;
  89857. for (var i = 0; i < vertex.triangleCount; ++i) {
  89858. var ref = this.references[vertex.triangleStart + i];
  89859. var t = this.triangles[ref.triangleId];
  89860. if (t.deleted)
  89861. continue;
  89862. if (deletedArray[i] && t.deletePending) {
  89863. t.deleted = true;
  89864. newDeleted++;
  89865. continue;
  89866. }
  89867. t.vertices[ref.vertexId] = origVertex;
  89868. t.isDirty = true;
  89869. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  89870. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  89871. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  89872. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  89873. this.references.push(ref);
  89874. }
  89875. return newDeleted;
  89876. };
  89877. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  89878. for (var i = 0; i < this.vertices.length; ++i) {
  89879. var vCount = [];
  89880. var vId = [];
  89881. var v = this.vertices[i];
  89882. var j;
  89883. for (j = 0; j < v.triangleCount; ++j) {
  89884. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  89885. for (var ii = 0; ii < 3; ii++) {
  89886. var ofs = 0;
  89887. var vv = triangle.vertices[ii];
  89888. while (ofs < vCount.length) {
  89889. if (vId[ofs] === vv.id)
  89890. break;
  89891. ++ofs;
  89892. }
  89893. if (ofs === vCount.length) {
  89894. vCount.push(1);
  89895. vId.push(vv.id);
  89896. }
  89897. else {
  89898. vCount[ofs]++;
  89899. }
  89900. }
  89901. }
  89902. for (j = 0; j < vCount.length; ++j) {
  89903. if (vCount[j] === 1) {
  89904. this.vertices[vId[j]].isBorder = true;
  89905. }
  89906. else {
  89907. this.vertices[vId[j]].isBorder = false;
  89908. }
  89909. }
  89910. }
  89911. };
  89912. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  89913. if (identifyBorders === void 0) { identifyBorders = false; }
  89914. var i;
  89915. if (!identifyBorders) {
  89916. var newTrianglesVector = [];
  89917. for (i = 0; i < this.triangles.length; ++i) {
  89918. if (!this.triangles[i].deleted) {
  89919. newTrianglesVector.push(this.triangles[i]);
  89920. }
  89921. }
  89922. this.triangles = newTrianglesVector;
  89923. }
  89924. for (i = 0; i < this.vertices.length; ++i) {
  89925. this.vertices[i].triangleCount = 0;
  89926. this.vertices[i].triangleStart = 0;
  89927. }
  89928. var t;
  89929. var j;
  89930. var v;
  89931. for (i = 0; i < this.triangles.length; ++i) {
  89932. t = this.triangles[i];
  89933. for (j = 0; j < 3; ++j) {
  89934. v = t.vertices[j];
  89935. v.triangleCount++;
  89936. }
  89937. }
  89938. var tStart = 0;
  89939. for (i = 0; i < this.vertices.length; ++i) {
  89940. this.vertices[i].triangleStart = tStart;
  89941. tStart += this.vertices[i].triangleCount;
  89942. this.vertices[i].triangleCount = 0;
  89943. }
  89944. var newReferences = new Array(this.triangles.length * 3);
  89945. for (i = 0; i < this.triangles.length; ++i) {
  89946. t = this.triangles[i];
  89947. for (j = 0; j < 3; ++j) {
  89948. v = t.vertices[j];
  89949. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  89950. v.triangleCount++;
  89951. }
  89952. }
  89953. this.references = newReferences;
  89954. if (identifyBorders) {
  89955. this.identifyBorder();
  89956. }
  89957. };
  89958. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  89959. var x = point.x;
  89960. var y = point.y;
  89961. var z = point.z;
  89962. 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
  89963. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  89964. };
  89965. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  89966. var q = vertex1.q.add(vertex2.q);
  89967. var border = vertex1.isBorder && vertex2.isBorder;
  89968. var error = 0;
  89969. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  89970. if (qDet !== 0 && !border) {
  89971. if (!pointResult) {
  89972. pointResult = BABYLON.Vector3.Zero();
  89973. }
  89974. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  89975. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  89976. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  89977. error = this.vertexError(q, pointResult);
  89978. }
  89979. else {
  89980. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  89981. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  89982. var error1 = this.vertexError(q, vertex1.position);
  89983. var error2 = this.vertexError(q, vertex2.position);
  89984. var error3 = this.vertexError(q, p3);
  89985. error = Math.min(error1, error2, error3);
  89986. if (error === error1) {
  89987. if (pointResult) {
  89988. pointResult.copyFrom(vertex1.position);
  89989. }
  89990. }
  89991. else if (error === error2) {
  89992. if (pointResult) {
  89993. pointResult.copyFrom(vertex2.position);
  89994. }
  89995. }
  89996. else {
  89997. if (pointResult) {
  89998. pointResult.copyFrom(p3);
  89999. }
  90000. }
  90001. }
  90002. return error;
  90003. };
  90004. return QuadraticErrorSimplification;
  90005. }());
  90006. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  90007. })(BABYLON || (BABYLON = {}));
  90008. //# sourceMappingURL=babylon.meshSimplification.js.map
  90009. var BABYLON;
  90010. (function (BABYLON) {
  90011. var MeshLODLevel = /** @class */ (function () {
  90012. function MeshLODLevel(distance, mesh) {
  90013. this.distance = distance;
  90014. this.mesh = mesh;
  90015. }
  90016. return MeshLODLevel;
  90017. }());
  90018. BABYLON.MeshLODLevel = MeshLODLevel;
  90019. })(BABYLON || (BABYLON = {}));
  90020. //# sourceMappingURL=babylon.meshLODLevel.js.map
  90021. var BABYLON;
  90022. (function (BABYLON) {
  90023. /**
  90024. * Defines the root class used to create scene optimization to use with SceneOptimizer
  90025. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90026. */
  90027. var SceneOptimization = /** @class */ (function () {
  90028. /**
  90029. * Creates the SceneOptimization object
  90030. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  90031. * @param desc defines the description associated with the optimization
  90032. */
  90033. function SceneOptimization(
  90034. /**
  90035. * Defines the priority of this optimization (0 by default which means first in the list)
  90036. */
  90037. priority) {
  90038. if (priority === void 0) { priority = 0; }
  90039. this.priority = priority;
  90040. }
  90041. /**
  90042. * Gets a string describing the action executed by the current optimization
  90043. * @returns description string
  90044. */
  90045. SceneOptimization.prototype.getDescription = function () {
  90046. return "";
  90047. };
  90048. /**
  90049. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90050. * @param scene defines the current scene where to apply this optimization
  90051. * @param optimizer defines the current optimizer
  90052. * @returns true if everything that can be done was applied
  90053. */
  90054. SceneOptimization.prototype.apply = function (scene, optimizer) {
  90055. return true;
  90056. };
  90057. ;
  90058. return SceneOptimization;
  90059. }());
  90060. BABYLON.SceneOptimization = SceneOptimization;
  90061. /**
  90062. * Defines an optimization used to reduce the size of render target textures
  90063. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90064. */
  90065. var TextureOptimization = /** @class */ (function (_super) {
  90066. __extends(TextureOptimization, _super);
  90067. /**
  90068. * Creates the TextureOptimization object
  90069. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  90070. * @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
  90071. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  90072. */
  90073. function TextureOptimization(
  90074. /**
  90075. * Defines the priority of this optimization (0 by default which means first in the list)
  90076. */
  90077. priority,
  90078. /**
  90079. * 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
  90080. */
  90081. maximumSize,
  90082. /**
  90083. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  90084. */
  90085. step) {
  90086. if (priority === void 0) { priority = 0; }
  90087. if (maximumSize === void 0) { maximumSize = 1024; }
  90088. if (step === void 0) { step = 0.5; }
  90089. var _this = _super.call(this, priority) || this;
  90090. _this.priority = priority;
  90091. _this.maximumSize = maximumSize;
  90092. _this.step = step;
  90093. return _this;
  90094. }
  90095. /**
  90096. * Gets a string describing the action executed by the current optimization
  90097. * @returns description string
  90098. */
  90099. TextureOptimization.prototype.getDescription = function () {
  90100. return "Reducing render target texture size to " + this.maximumSize;
  90101. };
  90102. /**
  90103. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90104. * @param scene defines the current scene where to apply this optimization
  90105. * @param optimizer defines the current optimizer
  90106. * @returns true if everything that can be done was applied
  90107. */
  90108. TextureOptimization.prototype.apply = function (scene, optimizer) {
  90109. var allDone = true;
  90110. for (var index = 0; index < scene.textures.length; index++) {
  90111. var texture = scene.textures[index];
  90112. if (!texture.canRescale || texture.getContext) {
  90113. continue;
  90114. }
  90115. var currentSize = texture.getSize();
  90116. var maxDimension = Math.max(currentSize.width, currentSize.height);
  90117. if (maxDimension > this.maximumSize) {
  90118. texture.scale(this.step);
  90119. allDone = false;
  90120. }
  90121. }
  90122. return allDone;
  90123. };
  90124. return TextureOptimization;
  90125. }(SceneOptimization));
  90126. BABYLON.TextureOptimization = TextureOptimization;
  90127. /**
  90128. * Defines an optimization used to increase or decrease the rendering resolution
  90129. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90130. */
  90131. var HardwareScalingOptimization = /** @class */ (function (_super) {
  90132. __extends(HardwareScalingOptimization, _super);
  90133. /**
  90134. * Creates the HardwareScalingOptimization object
  90135. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  90136. * @param maximumScale defines the maximum scale to use (2 by default)
  90137. * @param step defines the step to use between two passes (0.5 by default)
  90138. */
  90139. function HardwareScalingOptimization(
  90140. /**
  90141. * Defines the priority of this optimization (0 by default which means first in the list)
  90142. */
  90143. priority,
  90144. /**
  90145. * Defines the maximum scale to use (2 by default)
  90146. */
  90147. maximumScale,
  90148. /**
  90149. * Defines the step to use between two passes (0.5 by default)
  90150. */
  90151. step) {
  90152. if (priority === void 0) { priority = 0; }
  90153. if (maximumScale === void 0) { maximumScale = 2; }
  90154. if (step === void 0) { step = 0.25; }
  90155. var _this = _super.call(this, priority) || this;
  90156. _this.priority = priority;
  90157. _this.maximumScale = maximumScale;
  90158. _this.step = step;
  90159. _this._currentScale = -1;
  90160. _this._directionOffset = 1;
  90161. return _this;
  90162. }
  90163. /**
  90164. * Gets a string describing the action executed by the current optimization
  90165. * @return description string
  90166. */
  90167. HardwareScalingOptimization.prototype.getDescription = function () {
  90168. return "Setting hardware scaling level to " + this._currentScale;
  90169. };
  90170. /**
  90171. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90172. * @param scene defines the current scene where to apply this optimization
  90173. * @param optimizer defines the current optimizer
  90174. * @returns true if everything that can be done was applied
  90175. */
  90176. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  90177. if (this._currentScale === -1) {
  90178. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  90179. if (this._currentScale > this.maximumScale) {
  90180. this._directionOffset = -1;
  90181. }
  90182. }
  90183. this._currentScale += this._directionOffset * this.step;
  90184. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  90185. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  90186. };
  90187. ;
  90188. return HardwareScalingOptimization;
  90189. }(SceneOptimization));
  90190. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  90191. /**
  90192. * Defines an optimization used to remove shadows
  90193. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90194. */
  90195. var ShadowsOptimization = /** @class */ (function (_super) {
  90196. __extends(ShadowsOptimization, _super);
  90197. function ShadowsOptimization() {
  90198. return _super !== null && _super.apply(this, arguments) || this;
  90199. }
  90200. /**
  90201. * Gets a string describing the action executed by the current optimization
  90202. * @return description string
  90203. */
  90204. ShadowsOptimization.prototype.getDescription = function () {
  90205. return "Turning shadows on/off";
  90206. };
  90207. /**
  90208. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90209. * @param scene defines the current scene where to apply this optimization
  90210. * @param optimizer defines the current optimizer
  90211. * @returns true if everything that can be done was applied
  90212. */
  90213. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  90214. scene.shadowsEnabled = optimizer.isInImprovementMode;
  90215. return true;
  90216. };
  90217. ;
  90218. return ShadowsOptimization;
  90219. }(SceneOptimization));
  90220. BABYLON.ShadowsOptimization = ShadowsOptimization;
  90221. /**
  90222. * Defines an optimization used to turn post-processes off
  90223. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90224. */
  90225. var PostProcessesOptimization = /** @class */ (function (_super) {
  90226. __extends(PostProcessesOptimization, _super);
  90227. function PostProcessesOptimization() {
  90228. return _super !== null && _super.apply(this, arguments) || this;
  90229. }
  90230. /**
  90231. * Gets a string describing the action executed by the current optimization
  90232. * @return description string
  90233. */
  90234. PostProcessesOptimization.prototype.getDescription = function () {
  90235. return "Turning post-processes on/off";
  90236. };
  90237. /**
  90238. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90239. * @param scene defines the current scene where to apply this optimization
  90240. * @param optimizer defines the current optimizer
  90241. * @returns true if everything that can be done was applied
  90242. */
  90243. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  90244. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  90245. return true;
  90246. };
  90247. ;
  90248. return PostProcessesOptimization;
  90249. }(SceneOptimization));
  90250. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  90251. /**
  90252. * Defines an optimization used to turn lens flares off
  90253. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90254. */
  90255. var LensFlaresOptimization = /** @class */ (function (_super) {
  90256. __extends(LensFlaresOptimization, _super);
  90257. function LensFlaresOptimization() {
  90258. return _super !== null && _super.apply(this, arguments) || this;
  90259. }
  90260. /**
  90261. * Gets a string describing the action executed by the current optimization
  90262. * @return description string
  90263. */
  90264. LensFlaresOptimization.prototype.getDescription = function () {
  90265. return "Turning lens flares on/off";
  90266. };
  90267. /**
  90268. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90269. * @param scene defines the current scene where to apply this optimization
  90270. * @param optimizer defines the current optimizer
  90271. * @returns true if everything that can be done was applied
  90272. */
  90273. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  90274. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  90275. return true;
  90276. };
  90277. ;
  90278. return LensFlaresOptimization;
  90279. }(SceneOptimization));
  90280. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  90281. /**
  90282. * Defines an optimization based on user defined callback.
  90283. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90284. */
  90285. var CustomOptimization = /** @class */ (function (_super) {
  90286. __extends(CustomOptimization, _super);
  90287. function CustomOptimization() {
  90288. return _super !== null && _super.apply(this, arguments) || this;
  90289. }
  90290. /**
  90291. * Gets a string describing the action executed by the current optimization
  90292. * @returns description string
  90293. */
  90294. CustomOptimization.prototype.getDescription = function () {
  90295. if (this.onGetDescription) {
  90296. return this.onGetDescription();
  90297. }
  90298. return "Running user defined callback";
  90299. };
  90300. /**
  90301. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90302. * @param scene defines the current scene where to apply this optimization
  90303. * @param optimizer defines the current optimizer
  90304. * @returns true if everything that can be done was applied
  90305. */
  90306. CustomOptimization.prototype.apply = function (scene, optimizer) {
  90307. if (this.onApply) {
  90308. return this.onApply(scene, optimizer);
  90309. }
  90310. return true;
  90311. };
  90312. ;
  90313. return CustomOptimization;
  90314. }(SceneOptimization));
  90315. BABYLON.CustomOptimization = CustomOptimization;
  90316. /**
  90317. * Defines an optimization used to turn particles off
  90318. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90319. */
  90320. var ParticlesOptimization = /** @class */ (function (_super) {
  90321. __extends(ParticlesOptimization, _super);
  90322. function ParticlesOptimization() {
  90323. return _super !== null && _super.apply(this, arguments) || this;
  90324. }
  90325. /**
  90326. * Gets a string describing the action executed by the current optimization
  90327. * @return description string
  90328. */
  90329. ParticlesOptimization.prototype.getDescription = function () {
  90330. return "Turning particles on/off";
  90331. };
  90332. /**
  90333. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90334. * @param scene defines the current scene where to apply this optimization
  90335. * @param optimizer defines the current optimizer
  90336. * @returns true if everything that can be done was applied
  90337. */
  90338. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  90339. scene.particlesEnabled = optimizer.isInImprovementMode;
  90340. return true;
  90341. };
  90342. ;
  90343. return ParticlesOptimization;
  90344. }(SceneOptimization));
  90345. BABYLON.ParticlesOptimization = ParticlesOptimization;
  90346. /**
  90347. * Defines an optimization used to turn render targets off
  90348. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90349. */
  90350. var RenderTargetsOptimization = /** @class */ (function (_super) {
  90351. __extends(RenderTargetsOptimization, _super);
  90352. function RenderTargetsOptimization() {
  90353. return _super !== null && _super.apply(this, arguments) || this;
  90354. }
  90355. /**
  90356. * Gets a string describing the action executed by the current optimization
  90357. * @return description string
  90358. */
  90359. RenderTargetsOptimization.prototype.getDescription = function () {
  90360. return "Turning render targets off";
  90361. };
  90362. /**
  90363. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90364. * @param scene defines the current scene where to apply this optimization
  90365. * @param optimizer defines the current optimizer
  90366. * @returns true if everything that can be done was applied
  90367. */
  90368. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  90369. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  90370. return true;
  90371. };
  90372. ;
  90373. return RenderTargetsOptimization;
  90374. }(SceneOptimization));
  90375. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  90376. /**
  90377. * Defines an optimization used to merge meshes with compatible materials
  90378. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90379. */
  90380. var MergeMeshesOptimization = /** @class */ (function (_super) {
  90381. __extends(MergeMeshesOptimization, _super);
  90382. function MergeMeshesOptimization() {
  90383. var _this = _super !== null && _super.apply(this, arguments) || this;
  90384. _this._canBeMerged = function (abstractMesh) {
  90385. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  90386. return false;
  90387. }
  90388. var mesh = abstractMesh;
  90389. if (!mesh.isVisible || !mesh.isEnabled()) {
  90390. return false;
  90391. }
  90392. if (mesh.instances.length > 0) {
  90393. return false;
  90394. }
  90395. if (mesh.skeleton || mesh.hasLODLevels) {
  90396. return false;
  90397. }
  90398. if (mesh.parent) {
  90399. return false;
  90400. }
  90401. return true;
  90402. };
  90403. return _this;
  90404. }
  90405. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  90406. /**
  90407. * Gets or sets a boolean which defines if optimization octree has to be updated
  90408. */
  90409. get: function () {
  90410. return MergeMeshesOptimization._UpdateSelectionTree;
  90411. },
  90412. /**
  90413. * Gets or sets a boolean which defines if optimization octree has to be updated
  90414. */
  90415. set: function (value) {
  90416. MergeMeshesOptimization._UpdateSelectionTree = value;
  90417. },
  90418. enumerable: true,
  90419. configurable: true
  90420. });
  90421. /**
  90422. * Gets a string describing the action executed by the current optimization
  90423. * @return description string
  90424. */
  90425. MergeMeshesOptimization.prototype.getDescription = function () {
  90426. return "Merging similar meshes together";
  90427. };
  90428. /**
  90429. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90430. * @param scene defines the current scene where to apply this optimization
  90431. * @param optimizer defines the current optimizer
  90432. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  90433. * @returns true if everything that can be done was applied
  90434. */
  90435. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  90436. var globalPool = scene.meshes.slice(0);
  90437. var globalLength = globalPool.length;
  90438. for (var index = 0; index < globalLength; index++) {
  90439. var currentPool = new Array();
  90440. var current = globalPool[index];
  90441. // Checks
  90442. if (!this._canBeMerged(current)) {
  90443. continue;
  90444. }
  90445. currentPool.push(current);
  90446. // Find compatible meshes
  90447. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  90448. var otherMesh = globalPool[subIndex];
  90449. if (!this._canBeMerged(otherMesh)) {
  90450. continue;
  90451. }
  90452. if (otherMesh.material !== current.material) {
  90453. continue;
  90454. }
  90455. if (otherMesh.checkCollisions !== current.checkCollisions) {
  90456. continue;
  90457. }
  90458. currentPool.push(otherMesh);
  90459. globalLength--;
  90460. globalPool.splice(subIndex, 1);
  90461. subIndex--;
  90462. }
  90463. if (currentPool.length < 2) {
  90464. continue;
  90465. }
  90466. // Merge meshes
  90467. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  90468. }
  90469. if (updateSelectionTree != undefined) {
  90470. if (updateSelectionTree) {
  90471. scene.createOrUpdateSelectionOctree();
  90472. }
  90473. }
  90474. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  90475. scene.createOrUpdateSelectionOctree();
  90476. }
  90477. return true;
  90478. };
  90479. ;
  90480. MergeMeshesOptimization._UpdateSelectionTree = false;
  90481. return MergeMeshesOptimization;
  90482. }(SceneOptimization));
  90483. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  90484. /**
  90485. * Defines a list of options used by SceneOptimizer
  90486. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90487. */
  90488. var SceneOptimizerOptions = /** @class */ (function () {
  90489. /**
  90490. * Creates a new list of options used by SceneOptimizer
  90491. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  90492. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  90493. */
  90494. function SceneOptimizerOptions(
  90495. /**
  90496. * Defines the target frame rate to reach (60 by default)
  90497. */
  90498. targetFrameRate,
  90499. /**
  90500. * Defines the interval between two checkes (2000ms by default)
  90501. */
  90502. trackerDuration) {
  90503. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  90504. if (trackerDuration === void 0) { trackerDuration = 2000; }
  90505. this.targetFrameRate = targetFrameRate;
  90506. this.trackerDuration = trackerDuration;
  90507. /**
  90508. * Gets the list of optimizations to apply
  90509. */
  90510. this.optimizations = new Array();
  90511. }
  90512. /**
  90513. * Add a new optimization
  90514. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  90515. * @returns the current SceneOptimizerOptions
  90516. */
  90517. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  90518. this.optimizations.push(optimization);
  90519. return this;
  90520. };
  90521. /**
  90522. * Add a new custom optimization
  90523. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  90524. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  90525. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  90526. * @returns the current SceneOptimizerOptions
  90527. */
  90528. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  90529. if (priority === void 0) { priority = 0; }
  90530. var optimization = new CustomOptimization(priority);
  90531. optimization.onApply = onApply;
  90532. optimization.onGetDescription = onGetDescription;
  90533. this.optimizations.push(optimization);
  90534. return this;
  90535. };
  90536. /**
  90537. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  90538. * @param targetFrameRate defines the target frame rate (60 by default)
  90539. * @returns a SceneOptimizerOptions object
  90540. */
  90541. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  90542. var result = new SceneOptimizerOptions(targetFrameRate);
  90543. var priority = 0;
  90544. result.addOptimization(new MergeMeshesOptimization(priority));
  90545. result.addOptimization(new ShadowsOptimization(priority));
  90546. result.addOptimization(new LensFlaresOptimization(priority));
  90547. // Next priority
  90548. priority++;
  90549. result.addOptimization(new PostProcessesOptimization(priority));
  90550. result.addOptimization(new ParticlesOptimization(priority));
  90551. // Next priority
  90552. priority++;
  90553. result.addOptimization(new TextureOptimization(priority, 1024));
  90554. return result;
  90555. };
  90556. /**
  90557. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  90558. * @param targetFrameRate defines the target frame rate (60 by default)
  90559. * @returns a SceneOptimizerOptions object
  90560. */
  90561. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  90562. var result = new SceneOptimizerOptions(targetFrameRate);
  90563. var priority = 0;
  90564. result.addOptimization(new MergeMeshesOptimization(priority));
  90565. result.addOptimization(new ShadowsOptimization(priority));
  90566. result.addOptimization(new LensFlaresOptimization(priority));
  90567. // Next priority
  90568. priority++;
  90569. result.addOptimization(new PostProcessesOptimization(priority));
  90570. result.addOptimization(new ParticlesOptimization(priority));
  90571. // Next priority
  90572. priority++;
  90573. result.addOptimization(new TextureOptimization(priority, 512));
  90574. // Next priority
  90575. priority++;
  90576. result.addOptimization(new RenderTargetsOptimization(priority));
  90577. // Next priority
  90578. priority++;
  90579. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  90580. return result;
  90581. };
  90582. /**
  90583. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  90584. * @param targetFrameRate defines the target frame rate (60 by default)
  90585. * @returns a SceneOptimizerOptions object
  90586. */
  90587. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  90588. var result = new SceneOptimizerOptions(targetFrameRate);
  90589. var priority = 0;
  90590. result.addOptimization(new MergeMeshesOptimization(priority));
  90591. result.addOptimization(new ShadowsOptimization(priority));
  90592. result.addOptimization(new LensFlaresOptimization(priority));
  90593. // Next priority
  90594. priority++;
  90595. result.addOptimization(new PostProcessesOptimization(priority));
  90596. result.addOptimization(new ParticlesOptimization(priority));
  90597. // Next priority
  90598. priority++;
  90599. result.addOptimization(new TextureOptimization(priority, 256));
  90600. // Next priority
  90601. priority++;
  90602. result.addOptimization(new RenderTargetsOptimization(priority));
  90603. // Next priority
  90604. priority++;
  90605. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  90606. return result;
  90607. };
  90608. return SceneOptimizerOptions;
  90609. }());
  90610. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  90611. /**
  90612. * Class used to run optimizations in order to reach a target frame rate
  90613. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90614. */
  90615. var SceneOptimizer = /** @class */ (function () {
  90616. /**
  90617. * Creates a new SceneOptimizer
  90618. * @param scene defines the scene to work on
  90619. * @param options defines the options to use with the SceneOptimizer
  90620. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  90621. * @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)
  90622. */
  90623. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  90624. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  90625. if (improvementMode === void 0) { improvementMode = false; }
  90626. var _this = this;
  90627. this._isRunning = false;
  90628. this._currentPriorityLevel = 0;
  90629. this._targetFrameRate = 60;
  90630. this._trackerDuration = 2000;
  90631. this._currentFrameRate = 0;
  90632. this._improvementMode = false;
  90633. /**
  90634. * Defines an observable called when the optimizer reaches the target frame rate
  90635. */
  90636. this.onSuccessObservable = new BABYLON.Observable();
  90637. /**
  90638. * Defines an observable called when the optimizer enables an optimization
  90639. */
  90640. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  90641. /**
  90642. * Defines an observable called when the optimizer is not able to reach the target frame rate
  90643. */
  90644. this.onFailureObservable = new BABYLON.Observable();
  90645. if (!options) {
  90646. this._options = new SceneOptimizerOptions();
  90647. }
  90648. else {
  90649. this._options = options;
  90650. }
  90651. if (this._options.targetFrameRate) {
  90652. this._targetFrameRate = this._options.targetFrameRate;
  90653. }
  90654. if (this._options.trackerDuration) {
  90655. this._trackerDuration = this._options.trackerDuration;
  90656. }
  90657. if (autoGeneratePriorities) {
  90658. var priority = 0;
  90659. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  90660. var optim = _a[_i];
  90661. optim.priority = priority++;
  90662. }
  90663. }
  90664. this._improvementMode = improvementMode;
  90665. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  90666. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  90667. _this._sceneDisposeObserver = null;
  90668. _this.dispose();
  90669. });
  90670. }
  90671. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  90672. /**
  90673. * Gets a boolean indicating if the optimizer is in improvement mode
  90674. */
  90675. get: function () {
  90676. return this._improvementMode;
  90677. },
  90678. enumerable: true,
  90679. configurable: true
  90680. });
  90681. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  90682. /**
  90683. * Gets the current priority level (0 at start)
  90684. */
  90685. get: function () {
  90686. return this._currentPriorityLevel;
  90687. },
  90688. enumerable: true,
  90689. configurable: true
  90690. });
  90691. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  90692. /**
  90693. * Gets the current frame rate checked by the SceneOptimizer
  90694. */
  90695. get: function () {
  90696. return this._currentFrameRate;
  90697. },
  90698. enumerable: true,
  90699. configurable: true
  90700. });
  90701. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  90702. /**
  90703. * Gets or sets the current target frame rate (60 by default)
  90704. */
  90705. get: function () {
  90706. return this._targetFrameRate;
  90707. },
  90708. /**
  90709. * Gets or sets the current target frame rate (60 by default)
  90710. */
  90711. set: function (value) {
  90712. this._targetFrameRate = value;
  90713. },
  90714. enumerable: true,
  90715. configurable: true
  90716. });
  90717. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  90718. /**
  90719. * Gets or sets the current interval between two checks (every 2000ms by default)
  90720. */
  90721. get: function () {
  90722. return this._trackerDuration;
  90723. },
  90724. /**
  90725. * Gets or sets the current interval between two checks (every 2000ms by default)
  90726. */
  90727. set: function (value) {
  90728. this._trackerDuration = value;
  90729. },
  90730. enumerable: true,
  90731. configurable: true
  90732. });
  90733. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  90734. /**
  90735. * Gets the list of active optimizations
  90736. */
  90737. get: function () {
  90738. return this._options.optimizations;
  90739. },
  90740. enumerable: true,
  90741. configurable: true
  90742. });
  90743. /**
  90744. * Stops the current optimizer
  90745. */
  90746. SceneOptimizer.prototype.stop = function () {
  90747. this._isRunning = false;
  90748. };
  90749. /**
  90750. * Reset the optimizer to initial step (current priority level = 0)
  90751. */
  90752. SceneOptimizer.prototype.reset = function () {
  90753. this._currentPriorityLevel = 0;
  90754. };
  90755. /**
  90756. * Start the optimizer. By default it will try to reach a specific framerate
  90757. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  90758. */
  90759. SceneOptimizer.prototype.start = function () {
  90760. var _this = this;
  90761. if (this._isRunning) {
  90762. return;
  90763. }
  90764. this._isRunning = true;
  90765. // Let's wait for the scene to be ready before running our check
  90766. this._scene.executeWhenReady(function () {
  90767. setTimeout(function () {
  90768. _this._checkCurrentState();
  90769. }, _this._trackerDuration);
  90770. });
  90771. };
  90772. SceneOptimizer.prototype._checkCurrentState = function () {
  90773. var _this = this;
  90774. if (!this._isRunning) {
  90775. return;
  90776. }
  90777. var scene = this._scene;
  90778. var options = this._options;
  90779. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  90780. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  90781. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  90782. this._isRunning = false;
  90783. this.onSuccessObservable.notifyObservers(this);
  90784. return;
  90785. }
  90786. // Apply current level of optimizations
  90787. var allDone = true;
  90788. var noOptimizationApplied = true;
  90789. for (var index = 0; index < options.optimizations.length; index++) {
  90790. var optimization = options.optimizations[index];
  90791. if (optimization.priority === this._currentPriorityLevel) {
  90792. noOptimizationApplied = false;
  90793. allDone = allDone && optimization.apply(scene, this);
  90794. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  90795. }
  90796. }
  90797. // If no optimization was applied, this is a failure :(
  90798. if (noOptimizationApplied) {
  90799. this._isRunning = false;
  90800. this.onFailureObservable.notifyObservers(this);
  90801. return;
  90802. }
  90803. // If all optimizations were done, move to next level
  90804. if (allDone) {
  90805. this._currentPriorityLevel++;
  90806. }
  90807. // Let's the system running for a specific amount of time before checking FPS
  90808. scene.executeWhenReady(function () {
  90809. setTimeout(function () {
  90810. _this._checkCurrentState();
  90811. }, _this._trackerDuration);
  90812. });
  90813. };
  90814. /**
  90815. * Release all resources
  90816. */
  90817. SceneOptimizer.prototype.dispose = function () {
  90818. this.stop();
  90819. this.onSuccessObservable.clear();
  90820. this.onFailureObservable.clear();
  90821. this.onNewOptimizationAppliedObservable.clear();
  90822. if (this._sceneDisposeObserver) {
  90823. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  90824. }
  90825. };
  90826. /**
  90827. * Helper function to create a SceneOptimizer with one single line of code
  90828. * @param scene defines the scene to work on
  90829. * @param options defines the options to use with the SceneOptimizer
  90830. * @param onSuccess defines a callback to call on success
  90831. * @param onFailure defines a callback to call on failure
  90832. * @returns the new SceneOptimizer object
  90833. */
  90834. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  90835. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  90836. if (onSuccess) {
  90837. optimizer.onSuccessObservable.add(function () {
  90838. onSuccess();
  90839. });
  90840. }
  90841. if (onFailure) {
  90842. optimizer.onFailureObservable.add(function () {
  90843. onFailure();
  90844. });
  90845. }
  90846. optimizer.start();
  90847. return optimizer;
  90848. };
  90849. return SceneOptimizer;
  90850. }());
  90851. BABYLON.SceneOptimizer = SceneOptimizer;
  90852. })(BABYLON || (BABYLON = {}));
  90853. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  90854. var BABYLON;
  90855. (function (BABYLON) {
  90856. var OutlineRenderer = /** @class */ (function () {
  90857. function OutlineRenderer(scene) {
  90858. this.zOffset = 1;
  90859. this._scene = scene;
  90860. }
  90861. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  90862. var _this = this;
  90863. if (useOverlay === void 0) { useOverlay = false; }
  90864. var scene = this._scene;
  90865. var engine = this._scene.getEngine();
  90866. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  90867. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  90868. return;
  90869. }
  90870. var mesh = subMesh.getRenderingMesh();
  90871. var material = subMesh.getMaterial();
  90872. if (!material || !scene.activeCamera) {
  90873. return;
  90874. }
  90875. engine.enableEffect(this._effect);
  90876. // Logarithmic depth
  90877. if (material.useLogarithmicDepth) {
  90878. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  90879. }
  90880. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  90881. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  90882. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  90883. // Bones
  90884. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  90885. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  90886. }
  90887. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  90888. // Alpha test
  90889. if (material && material.needAlphaTesting()) {
  90890. var alphaTexture = material.getAlphaTestTexture();
  90891. if (alphaTexture) {
  90892. this._effect.setTexture("diffuseSampler", alphaTexture);
  90893. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  90894. }
  90895. }
  90896. engine.setZOffset(-this.zOffset);
  90897. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  90898. engine.setZOffset(0);
  90899. };
  90900. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  90901. var defines = [];
  90902. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  90903. var mesh = subMesh.getMesh();
  90904. var material = subMesh.getMaterial();
  90905. if (material) {
  90906. // Alpha test
  90907. if (material.needAlphaTesting()) {
  90908. defines.push("#define ALPHATEST");
  90909. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  90910. attribs.push(BABYLON.VertexBuffer.UVKind);
  90911. defines.push("#define UV1");
  90912. }
  90913. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  90914. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  90915. defines.push("#define UV2");
  90916. }
  90917. }
  90918. //Logarithmic depth
  90919. if (material.useLogarithmicDepth) {
  90920. defines.push("#define LOGARITHMICDEPTH");
  90921. }
  90922. }
  90923. // Bones
  90924. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  90925. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  90926. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  90927. if (mesh.numBoneInfluencers > 4) {
  90928. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  90929. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  90930. }
  90931. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  90932. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  90933. }
  90934. else {
  90935. defines.push("#define NUM_BONE_INFLUENCERS 0");
  90936. }
  90937. // Instances
  90938. if (useInstances) {
  90939. defines.push("#define INSTANCES");
  90940. attribs.push("world0");
  90941. attribs.push("world1");
  90942. attribs.push("world2");
  90943. attribs.push("world3");
  90944. }
  90945. // Get correct effect
  90946. var join = defines.join("\n");
  90947. if (this._cachedDefines !== join) {
  90948. this._cachedDefines = join;
  90949. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  90950. }
  90951. return this._effect.isReady();
  90952. };
  90953. return OutlineRenderer;
  90954. }());
  90955. BABYLON.OutlineRenderer = OutlineRenderer;
  90956. })(BABYLON || (BABYLON = {}));
  90957. //# sourceMappingURL=babylon.outlineRenderer.js.map
  90958. var BABYLON;
  90959. (function (BABYLON) {
  90960. var FaceAdjacencies = /** @class */ (function () {
  90961. function FaceAdjacencies() {
  90962. this.edges = new Array();
  90963. this.edgesConnectedCount = 0;
  90964. }
  90965. return FaceAdjacencies;
  90966. }());
  90967. var EdgesRenderer = /** @class */ (function () {
  90968. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  90969. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  90970. if (epsilon === void 0) { epsilon = 0.95; }
  90971. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  90972. this.edgesWidthScalerForOrthographic = 1000.0;
  90973. this.edgesWidthScalerForPerspective = 50.0;
  90974. this._linesPositions = new Array();
  90975. this._linesNormals = new Array();
  90976. this._linesIndices = new Array();
  90977. this._buffers = {};
  90978. this._checkVerticesInsteadOfIndices = false;
  90979. this._source = source;
  90980. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  90981. this._epsilon = epsilon;
  90982. this._prepareRessources();
  90983. this._generateEdgesLines();
  90984. }
  90985. EdgesRenderer.prototype._prepareRessources = function () {
  90986. if (this._lineShader) {
  90987. return;
  90988. }
  90989. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  90990. attributes: ["position", "normal"],
  90991. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  90992. });
  90993. this._lineShader.disableDepthWrite = true;
  90994. this._lineShader.backFaceCulling = false;
  90995. };
  90996. EdgesRenderer.prototype._rebuild = function () {
  90997. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  90998. if (buffer) {
  90999. buffer._rebuild();
  91000. }
  91001. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  91002. if (buffer) {
  91003. buffer._rebuild();
  91004. }
  91005. var scene = this._source.getScene();
  91006. var engine = scene.getEngine();
  91007. this._ib = engine.createIndexBuffer(this._linesIndices);
  91008. };
  91009. EdgesRenderer.prototype.dispose = function () {
  91010. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  91011. if (buffer) {
  91012. buffer.dispose();
  91013. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  91014. }
  91015. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  91016. if (buffer) {
  91017. buffer.dispose();
  91018. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  91019. }
  91020. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  91021. this._lineShader.dispose();
  91022. };
  91023. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  91024. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  91025. return 0;
  91026. }
  91027. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  91028. return 1;
  91029. }
  91030. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  91031. return 2;
  91032. }
  91033. return -1;
  91034. };
  91035. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  91036. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  91037. return 0;
  91038. }
  91039. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  91040. return 1;
  91041. }
  91042. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  91043. return 2;
  91044. }
  91045. return -1;
  91046. };
  91047. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  91048. var needToCreateLine;
  91049. if (edge === undefined) {
  91050. needToCreateLine = true;
  91051. }
  91052. else {
  91053. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  91054. needToCreateLine = dotProduct < this._epsilon;
  91055. }
  91056. if (needToCreateLine) {
  91057. var offset = this._linesPositions.length / 3;
  91058. var normal = p0.subtract(p1);
  91059. normal.normalize();
  91060. // Positions
  91061. this._linesPositions.push(p0.x);
  91062. this._linesPositions.push(p0.y);
  91063. this._linesPositions.push(p0.z);
  91064. this._linesPositions.push(p0.x);
  91065. this._linesPositions.push(p0.y);
  91066. this._linesPositions.push(p0.z);
  91067. this._linesPositions.push(p1.x);
  91068. this._linesPositions.push(p1.y);
  91069. this._linesPositions.push(p1.z);
  91070. this._linesPositions.push(p1.x);
  91071. this._linesPositions.push(p1.y);
  91072. this._linesPositions.push(p1.z);
  91073. // Normals
  91074. this._linesNormals.push(p1.x);
  91075. this._linesNormals.push(p1.y);
  91076. this._linesNormals.push(p1.z);
  91077. this._linesNormals.push(-1);
  91078. this._linesNormals.push(p1.x);
  91079. this._linesNormals.push(p1.y);
  91080. this._linesNormals.push(p1.z);
  91081. this._linesNormals.push(1);
  91082. this._linesNormals.push(p0.x);
  91083. this._linesNormals.push(p0.y);
  91084. this._linesNormals.push(p0.z);
  91085. this._linesNormals.push(-1);
  91086. this._linesNormals.push(p0.x);
  91087. this._linesNormals.push(p0.y);
  91088. this._linesNormals.push(p0.z);
  91089. this._linesNormals.push(1);
  91090. // Indices
  91091. this._linesIndices.push(offset);
  91092. this._linesIndices.push(offset + 1);
  91093. this._linesIndices.push(offset + 2);
  91094. this._linesIndices.push(offset);
  91095. this._linesIndices.push(offset + 2);
  91096. this._linesIndices.push(offset + 3);
  91097. }
  91098. };
  91099. EdgesRenderer.prototype._generateEdgesLines = function () {
  91100. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  91101. var indices = this._source.getIndices();
  91102. if (!indices || !positions) {
  91103. return;
  91104. }
  91105. // First let's find adjacencies
  91106. var adjacencies = new Array();
  91107. var faceNormals = new Array();
  91108. var index;
  91109. var faceAdjacencies;
  91110. // Prepare faces
  91111. for (index = 0; index < indices.length; index += 3) {
  91112. faceAdjacencies = new FaceAdjacencies();
  91113. var p0Index = indices[index];
  91114. var p1Index = indices[index + 1];
  91115. var p2Index = indices[index + 2];
  91116. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  91117. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  91118. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  91119. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  91120. faceNormal.normalize();
  91121. faceNormals.push(faceNormal);
  91122. adjacencies.push(faceAdjacencies);
  91123. }
  91124. // Scan
  91125. for (index = 0; index < adjacencies.length; index++) {
  91126. faceAdjacencies = adjacencies[index];
  91127. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  91128. var otherFaceAdjacencies = adjacencies[otherIndex];
  91129. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  91130. break;
  91131. }
  91132. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  91133. continue;
  91134. }
  91135. var otherP0 = indices[otherIndex * 3];
  91136. var otherP1 = indices[otherIndex * 3 + 1];
  91137. var otherP2 = indices[otherIndex * 3 + 2];
  91138. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  91139. var otherEdgeIndex = 0;
  91140. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  91141. continue;
  91142. }
  91143. switch (edgeIndex) {
  91144. case 0:
  91145. if (this._checkVerticesInsteadOfIndices) {
  91146. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  91147. }
  91148. else {
  91149. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  91150. }
  91151. break;
  91152. case 1:
  91153. if (this._checkVerticesInsteadOfIndices) {
  91154. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  91155. }
  91156. else {
  91157. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  91158. }
  91159. break;
  91160. case 2:
  91161. if (this._checkVerticesInsteadOfIndices) {
  91162. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  91163. }
  91164. else {
  91165. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  91166. }
  91167. break;
  91168. }
  91169. if (otherEdgeIndex === -1) {
  91170. continue;
  91171. }
  91172. faceAdjacencies.edges[edgeIndex] = otherIndex;
  91173. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  91174. faceAdjacencies.edgesConnectedCount++;
  91175. otherFaceAdjacencies.edgesConnectedCount++;
  91176. if (faceAdjacencies.edgesConnectedCount === 3) {
  91177. break;
  91178. }
  91179. }
  91180. }
  91181. }
  91182. // Create lines
  91183. for (index = 0; index < adjacencies.length; index++) {
  91184. // 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
  91185. var current = adjacencies[index];
  91186. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  91187. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  91188. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  91189. }
  91190. // Merge into a single mesh
  91191. var engine = this._source.getScene().getEngine();
  91192. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  91193. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  91194. this._ib = engine.createIndexBuffer(this._linesIndices);
  91195. this._indicesCount = this._linesIndices.length;
  91196. };
  91197. EdgesRenderer.prototype.render = function () {
  91198. var scene = this._source.getScene();
  91199. if (!this._lineShader.isReady() || !scene.activeCamera) {
  91200. return;
  91201. }
  91202. var engine = scene.getEngine();
  91203. this._lineShader._preBind();
  91204. // VBOs
  91205. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  91206. scene.resetCachedMaterial();
  91207. this._lineShader.setColor4("color", this._source.edgesColor);
  91208. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  91209. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  91210. }
  91211. else {
  91212. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  91213. }
  91214. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  91215. this._lineShader.bind(this._source.getWorldMatrix());
  91216. // Draw order
  91217. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  91218. this._lineShader.unbind();
  91219. engine.setDepthWrite(true);
  91220. };
  91221. return EdgesRenderer;
  91222. }());
  91223. BABYLON.EdgesRenderer = EdgesRenderer;
  91224. })(BABYLON || (BABYLON = {}));
  91225. //# sourceMappingURL=babylon.edgesRenderer.js.map
  91226. var __assign = (this && this.__assign) || Object.assign || function(t) {
  91227. for (var s, i = 1, n = arguments.length; i < n; i++) {
  91228. s = arguments[i];
  91229. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  91230. t[p] = s[p];
  91231. }
  91232. return t;
  91233. };
  91234. var BABYLON;
  91235. (function (BABYLON) {
  91236. /**
  91237. * The effect layer Helps adding post process effect blended with the main pass.
  91238. *
  91239. * This can be for instance use to generate glow or higlight effects on the scene.
  91240. *
  91241. * The effect layer class can not be used directly and is intented to inherited from to be
  91242. * customized per effects.
  91243. */
  91244. var EffectLayer = /** @class */ (function () {
  91245. /**
  91246. * Instantiates a new effect Layer and references it in the scene.
  91247. * @param name The name of the layer
  91248. * @param scene The scene to use the layer in
  91249. */
  91250. function EffectLayer(
  91251. /** The Friendly of the effect in the scene */
  91252. name, scene) {
  91253. this._vertexBuffers = {};
  91254. this._maxSize = 0;
  91255. this._mainTextureDesiredSize = { width: 0, height: 0 };
  91256. this._shouldRender = true;
  91257. this._postProcesses = [];
  91258. this._textures = [];
  91259. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  91260. /**
  91261. * The clear color of the texture used to generate the glow map.
  91262. */
  91263. this.neutralColor = new BABYLON.Color4();
  91264. /**
  91265. * Specifies wether the highlight layer is enabled or not.
  91266. */
  91267. this.isEnabled = true;
  91268. /**
  91269. * An event triggered when the effect layer has been disposed.
  91270. */
  91271. this.onDisposeObservable = new BABYLON.Observable();
  91272. /**
  91273. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  91274. */
  91275. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  91276. /**
  91277. * An event triggered when the generated texture is being merged in the scene.
  91278. */
  91279. this.onBeforeComposeObservable = new BABYLON.Observable();
  91280. /**
  91281. * An event triggered when the generated texture has been merged in the scene.
  91282. */
  91283. this.onAfterComposeObservable = new BABYLON.Observable();
  91284. /**
  91285. * An event triggered when the efffect layer changes its size.
  91286. */
  91287. this.onSizeChangedObservable = new BABYLON.Observable();
  91288. this.name = name;
  91289. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  91290. this._engine = scene.getEngine();
  91291. this._maxSize = this._engine.getCaps().maxTextureSize;
  91292. this._scene.effectLayers.push(this);
  91293. // Generate Buffers
  91294. this._generateIndexBuffer();
  91295. this._genrateVertexBuffer();
  91296. }
  91297. Object.defineProperty(EffectLayer.prototype, "camera", {
  91298. /**
  91299. * Gets the camera attached to the layer.
  91300. */
  91301. get: function () {
  91302. return this._effectLayerOptions.camera;
  91303. },
  91304. enumerable: true,
  91305. configurable: true
  91306. });
  91307. /**
  91308. * Initializes the effect layer with the required options.
  91309. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  91310. */
  91311. EffectLayer.prototype._init = function (options) {
  91312. // Adapt options
  91313. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  91314. this._setMainTextureSize();
  91315. this._createMainTexture();
  91316. this._createTextureAndPostProcesses();
  91317. this._mergeEffect = this._createMergeEffect();
  91318. };
  91319. /**
  91320. * Generates the index buffer of the full screen quad blending to the main canvas.
  91321. */
  91322. EffectLayer.prototype._generateIndexBuffer = function () {
  91323. // Indices
  91324. var indices = [];
  91325. indices.push(0);
  91326. indices.push(1);
  91327. indices.push(2);
  91328. indices.push(0);
  91329. indices.push(2);
  91330. indices.push(3);
  91331. this._indexBuffer = this._engine.createIndexBuffer(indices);
  91332. };
  91333. /**
  91334. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  91335. */
  91336. EffectLayer.prototype._genrateVertexBuffer = function () {
  91337. // VBO
  91338. var vertices = [];
  91339. vertices.push(1, 1);
  91340. vertices.push(-1, 1);
  91341. vertices.push(-1, -1);
  91342. vertices.push(1, -1);
  91343. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  91344. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  91345. };
  91346. /**
  91347. * Sets the main texture desired size which is the closest power of two
  91348. * of the engine canvas size.
  91349. */
  91350. EffectLayer.prototype._setMainTextureSize = function () {
  91351. if (this._effectLayerOptions.mainTextureFixedSize) {
  91352. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  91353. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  91354. }
  91355. else {
  91356. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  91357. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  91358. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  91359. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  91360. }
  91361. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  91362. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  91363. };
  91364. /**
  91365. * Creates the main texture for the effect layer.
  91366. */
  91367. EffectLayer.prototype._createMainTexture = function () {
  91368. var _this = this;
  91369. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  91370. width: this._mainTextureDesiredSize.width,
  91371. height: this._mainTextureDesiredSize.height
  91372. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  91373. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  91374. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91375. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91376. this._mainTexture.anisotropicFilteringLevel = 1;
  91377. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  91378. this._mainTexture.renderParticles = false;
  91379. this._mainTexture.renderList = null;
  91380. this._mainTexture.ignoreCameraViewport = true;
  91381. // Custom render function
  91382. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  91383. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  91384. var index;
  91385. var engine = _this._scene.getEngine();
  91386. if (depthOnlySubMeshes.length) {
  91387. engine.setColorWrite(false);
  91388. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  91389. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  91390. }
  91391. engine.setColorWrite(true);
  91392. }
  91393. for (index = 0; index < opaqueSubMeshes.length; index++) {
  91394. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  91395. }
  91396. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  91397. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  91398. }
  91399. for (index = 0; index < transparentSubMeshes.length; index++) {
  91400. _this._renderSubMesh(transparentSubMeshes.data[index]);
  91401. }
  91402. };
  91403. this._mainTexture.onClearObservable.add(function (engine) {
  91404. engine.clear(_this.neutralColor, true, true, true);
  91405. });
  91406. };
  91407. /**
  91408. * Checks for the readiness of the element composing the layer.
  91409. * @param subMesh the mesh to check for
  91410. * @param useInstances specify wether or not to use instances to render the mesh
  91411. * @param emissiveTexture the associated emissive texture used to generate the glow
  91412. * @return true if ready otherwise, false
  91413. */
  91414. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  91415. var material = subMesh.getMaterial();
  91416. if (!material) {
  91417. return false;
  91418. }
  91419. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  91420. return false;
  91421. }
  91422. var defines = [];
  91423. var attribs = [BABYLON.VertexBuffer.PositionKind];
  91424. var mesh = subMesh.getMesh();
  91425. var uv1 = false;
  91426. var uv2 = false;
  91427. // Alpha test
  91428. if (material && material.needAlphaTesting()) {
  91429. var alphaTexture = material.getAlphaTestTexture();
  91430. if (alphaTexture) {
  91431. defines.push("#define ALPHATEST");
  91432. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  91433. alphaTexture.coordinatesIndex === 1) {
  91434. defines.push("#define DIFFUSEUV2");
  91435. uv2 = true;
  91436. }
  91437. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  91438. defines.push("#define DIFFUSEUV1");
  91439. uv1 = true;
  91440. }
  91441. }
  91442. }
  91443. // Emissive
  91444. if (emissiveTexture) {
  91445. defines.push("#define EMISSIVE");
  91446. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  91447. emissiveTexture.coordinatesIndex === 1) {
  91448. defines.push("#define EMISSIVEUV2");
  91449. uv2 = true;
  91450. }
  91451. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  91452. defines.push("#define EMISSIVEUV1");
  91453. uv1 = true;
  91454. }
  91455. }
  91456. if (uv1) {
  91457. attribs.push(BABYLON.VertexBuffer.UVKind);
  91458. defines.push("#define UV1");
  91459. }
  91460. if (uv2) {
  91461. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  91462. defines.push("#define UV2");
  91463. }
  91464. // Bones
  91465. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  91466. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  91467. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  91468. if (mesh.numBoneInfluencers > 4) {
  91469. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  91470. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  91471. }
  91472. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  91473. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  91474. }
  91475. else {
  91476. defines.push("#define NUM_BONE_INFLUENCERS 0");
  91477. }
  91478. // Morph targets
  91479. var manager = mesh.morphTargetManager;
  91480. var morphInfluencers = 0;
  91481. if (manager) {
  91482. if (manager.numInfluencers > 0) {
  91483. defines.push("#define MORPHTARGETS");
  91484. morphInfluencers = manager.numInfluencers;
  91485. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  91486. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  91487. }
  91488. }
  91489. // Instances
  91490. if (useInstances) {
  91491. defines.push("#define INSTANCES");
  91492. attribs.push("world0");
  91493. attribs.push("world1");
  91494. attribs.push("world2");
  91495. attribs.push("world3");
  91496. }
  91497. // Get correct effect
  91498. var join = defines.join("\n");
  91499. if (this._cachedDefines !== join) {
  91500. this._cachedDefines = join;
  91501. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  91502. }
  91503. return this._effectLayerMapGenerationEffect.isReady();
  91504. };
  91505. /**
  91506. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  91507. */
  91508. EffectLayer.prototype.render = function () {
  91509. var currentEffect = this._mergeEffect;
  91510. // Check
  91511. if (!currentEffect.isReady())
  91512. return;
  91513. for (var i = 0; i < this._postProcesses.length; i++) {
  91514. if (!this._postProcesses[i].isReady()) {
  91515. return;
  91516. }
  91517. }
  91518. var engine = this._scene.getEngine();
  91519. this.onBeforeComposeObservable.notifyObservers(this);
  91520. // Render
  91521. engine.enableEffect(currentEffect);
  91522. engine.setState(false);
  91523. // VBOs
  91524. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  91525. // Cache
  91526. var previousAlphaMode = engine.getAlphaMode();
  91527. // Go Blend.
  91528. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  91529. // Blends the map on the main canvas.
  91530. this._internalRender(currentEffect);
  91531. // Restore Alpha
  91532. engine.setAlphaMode(previousAlphaMode);
  91533. this.onAfterComposeObservable.notifyObservers(this);
  91534. // Handle size changes.
  91535. var size = this._mainTexture.getSize();
  91536. this._setMainTextureSize();
  91537. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  91538. // Recreate RTT and post processes on size change.
  91539. this.onSizeChangedObservable.notifyObservers(this);
  91540. this._disposeTextureAndPostProcesses();
  91541. this._createMainTexture();
  91542. this._createTextureAndPostProcesses();
  91543. }
  91544. };
  91545. /**
  91546. * Determine if a given mesh will be used in the current effect.
  91547. * @param mesh mesh to test
  91548. * @returns true if the mesh will be used
  91549. */
  91550. EffectLayer.prototype.hasMesh = function (mesh) {
  91551. return true;
  91552. };
  91553. /**
  91554. * Returns true if the layer contains information to display, otherwise false.
  91555. * @returns true if the glow layer should be rendered
  91556. */
  91557. EffectLayer.prototype.shouldRender = function () {
  91558. return this.isEnabled && this._shouldRender;
  91559. };
  91560. /**
  91561. * Returns true if the mesh should render, otherwise false.
  91562. * @param mesh The mesh to render
  91563. * @returns true if it should render otherwise false
  91564. */
  91565. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  91566. return true;
  91567. };
  91568. /**
  91569. * Returns true if the mesh should render, otherwise false.
  91570. * @param mesh The mesh to render
  91571. * @returns true if it should render otherwise false
  91572. */
  91573. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  91574. return true;
  91575. };
  91576. /**
  91577. * Renders the submesh passed in parameter to the generation map.
  91578. */
  91579. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  91580. var _this = this;
  91581. if (!this.shouldRender()) {
  91582. return;
  91583. }
  91584. var material = subMesh.getMaterial();
  91585. var mesh = subMesh.getRenderingMesh();
  91586. var scene = this._scene;
  91587. var engine = scene.getEngine();
  91588. if (!material) {
  91589. return;
  91590. }
  91591. // Do not block in blend mode.
  91592. if (material.needAlphaBlendingForMesh(mesh)) {
  91593. return;
  91594. }
  91595. // Culling
  91596. engine.setState(material.backFaceCulling);
  91597. // Managing instances
  91598. var batch = mesh._getInstancesRenderList(subMesh._id);
  91599. if (batch.mustReturn) {
  91600. return;
  91601. }
  91602. // Early Exit per mesh
  91603. if (!this._shouldRenderMesh(mesh)) {
  91604. return;
  91605. }
  91606. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  91607. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  91608. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  91609. engine.enableEffect(this._effectLayerMapGenerationEffect);
  91610. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  91611. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  91612. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  91613. // Alpha test
  91614. if (material && material.needAlphaTesting()) {
  91615. var alphaTexture = material.getAlphaTestTexture();
  91616. if (alphaTexture) {
  91617. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  91618. var textureMatrix = alphaTexture.getTextureMatrix();
  91619. if (textureMatrix) {
  91620. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  91621. }
  91622. }
  91623. }
  91624. // Glow emissive only
  91625. if (this._emissiveTextureAndColor.texture) {
  91626. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  91627. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  91628. }
  91629. // Bones
  91630. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  91631. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  91632. }
  91633. // Morph targets
  91634. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  91635. // Draw
  91636. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  91637. }
  91638. else {
  91639. // Need to reset refresh rate of the shadowMap
  91640. this._mainTexture.resetRefreshCounter();
  91641. }
  91642. };
  91643. /**
  91644. * Rebuild the required buffers.
  91645. * @hidden Internal use only.
  91646. */
  91647. EffectLayer.prototype._rebuild = function () {
  91648. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  91649. if (vb) {
  91650. vb._rebuild();
  91651. }
  91652. this._generateIndexBuffer();
  91653. };
  91654. /**
  91655. * Dispose only the render target textures and post process.
  91656. */
  91657. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  91658. this._mainTexture.dispose();
  91659. for (var i = 0; i < this._postProcesses.length; i++) {
  91660. if (this._postProcesses[i]) {
  91661. this._postProcesses[i].dispose();
  91662. }
  91663. }
  91664. this._postProcesses = [];
  91665. for (var i = 0; i < this._textures.length; i++) {
  91666. if (this._textures[i]) {
  91667. this._textures[i].dispose();
  91668. }
  91669. }
  91670. this._textures = [];
  91671. };
  91672. /**
  91673. * Dispose the highlight layer and free resources.
  91674. */
  91675. EffectLayer.prototype.dispose = function () {
  91676. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  91677. if (vertexBuffer) {
  91678. vertexBuffer.dispose();
  91679. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  91680. }
  91681. if (this._indexBuffer) {
  91682. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  91683. this._indexBuffer = null;
  91684. }
  91685. // Clean textures and post processes
  91686. this._disposeTextureAndPostProcesses();
  91687. // Remove from scene
  91688. var index = this._scene.effectLayers.indexOf(this, 0);
  91689. if (index > -1) {
  91690. this._scene.effectLayers.splice(index, 1);
  91691. }
  91692. // Callback
  91693. this.onDisposeObservable.notifyObservers(this);
  91694. this.onDisposeObservable.clear();
  91695. this.onBeforeRenderMainTextureObservable.clear();
  91696. this.onBeforeComposeObservable.clear();
  91697. this.onAfterComposeObservable.clear();
  91698. this.onSizeChangedObservable.clear();
  91699. };
  91700. /**
  91701. * Gets the class name of the effect layer
  91702. * @returns the string with the class name of the effect layer
  91703. */
  91704. EffectLayer.prototype.getClassName = function () {
  91705. return "EffectLayer";
  91706. };
  91707. /**
  91708. * Creates an effect layer from parsed effect layer data
  91709. * @param parsedEffectLayer defines effect layer data
  91710. * @param scene defines the current scene
  91711. * @param rootUrl defines the root URL containing the effect layer information
  91712. * @returns a parsed effect Layer
  91713. */
  91714. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  91715. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  91716. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  91717. };
  91718. __decorate([
  91719. BABYLON.serialize()
  91720. ], EffectLayer.prototype, "name", void 0);
  91721. __decorate([
  91722. BABYLON.serializeAsColor4()
  91723. ], EffectLayer.prototype, "neutralColor", void 0);
  91724. __decorate([
  91725. BABYLON.serialize()
  91726. ], EffectLayer.prototype, "isEnabled", void 0);
  91727. __decorate([
  91728. BABYLON.serializeAsCameraReference()
  91729. ], EffectLayer.prototype, "camera", null);
  91730. return EffectLayer;
  91731. }());
  91732. BABYLON.EffectLayer = EffectLayer;
  91733. })(BABYLON || (BABYLON = {}));
  91734. //# sourceMappingURL=babylon.effectLayer.js.map
  91735. var BABYLON;
  91736. (function (BABYLON) {
  91737. /**
  91738. * Special Glow Blur post process only blurring the alpha channel
  91739. * It enforces keeping the most luminous color in the color channel.
  91740. */
  91741. var GlowBlurPostProcess = /** @class */ (function (_super) {
  91742. __extends(GlowBlurPostProcess, _super);
  91743. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  91744. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  91745. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  91746. _this.direction = direction;
  91747. _this.kernel = kernel;
  91748. _this.onApplyObservable.add(function (effect) {
  91749. effect.setFloat2("screenSize", _this.width, _this.height);
  91750. effect.setVector2("direction", _this.direction);
  91751. effect.setFloat("blurWidth", _this.kernel);
  91752. });
  91753. return _this;
  91754. }
  91755. return GlowBlurPostProcess;
  91756. }(BABYLON.PostProcess));
  91757. /**
  91758. * The highlight layer Helps adding a glow effect around a mesh.
  91759. *
  91760. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  91761. * glowy meshes to your scene.
  91762. *
  91763. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  91764. */
  91765. var HighlightLayer = /** @class */ (function (_super) {
  91766. __extends(HighlightLayer, _super);
  91767. /**
  91768. * Instantiates a new highlight Layer and references it to the scene..
  91769. * @param name The name of the layer
  91770. * @param scene The scene to use the layer in
  91771. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  91772. */
  91773. function HighlightLayer(name, scene, options) {
  91774. var _this = _super.call(this, name, scene) || this;
  91775. _this.name = name;
  91776. /**
  91777. * Specifies whether or not the inner glow is ACTIVE in the layer.
  91778. */
  91779. _this.innerGlow = true;
  91780. /**
  91781. * Specifies whether or not the outer glow is ACTIVE in the layer.
  91782. */
  91783. _this.outerGlow = true;
  91784. /**
  91785. * An event triggered when the highlight layer is being blurred.
  91786. */
  91787. _this.onBeforeBlurObservable = new BABYLON.Observable();
  91788. /**
  91789. * An event triggered when the highlight layer has been blurred.
  91790. */
  91791. _this.onAfterBlurObservable = new BABYLON.Observable();
  91792. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  91793. _this._meshes = {};
  91794. _this._excludedMeshes = {};
  91795. _this.neutralColor = HighlightLayer.NeutralColor;
  91796. // Warn on stencil
  91797. if (!_this._engine.isStencilEnable) {
  91798. 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 }");
  91799. }
  91800. // Adapt options
  91801. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  91802. // Initialize the layer
  91803. _this._init({
  91804. alphaBlendingMode: _this._options.alphaBlendingMode,
  91805. camera: _this._options.camera,
  91806. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  91807. mainTextureRatio: _this._options.mainTextureRatio
  91808. });
  91809. // Do not render as long as no meshes have been added
  91810. _this._shouldRender = false;
  91811. return _this;
  91812. }
  91813. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  91814. /**
  91815. * Gets the horizontal size of the blur.
  91816. */
  91817. get: function () {
  91818. return this._horizontalBlurPostprocess.kernel;
  91819. },
  91820. /**
  91821. * Specifies the horizontal size of the blur.
  91822. */
  91823. set: function (value) {
  91824. this._horizontalBlurPostprocess.kernel = value;
  91825. },
  91826. enumerable: true,
  91827. configurable: true
  91828. });
  91829. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  91830. /**
  91831. * Gets the vertical size of the blur.
  91832. */
  91833. get: function () {
  91834. return this._verticalBlurPostprocess.kernel;
  91835. },
  91836. /**
  91837. * Specifies the vertical size of the blur.
  91838. */
  91839. set: function (value) {
  91840. this._verticalBlurPostprocess.kernel = value;
  91841. },
  91842. enumerable: true,
  91843. configurable: true
  91844. });
  91845. /**
  91846. * Get the effect name of the layer.
  91847. * @return The effect name
  91848. */
  91849. HighlightLayer.prototype.getEffectName = function () {
  91850. return HighlightLayer.EffectName;
  91851. };
  91852. /**
  91853. * Create the merge effect. This is the shader use to blit the information back
  91854. * to the main canvas at the end of the scene rendering.
  91855. */
  91856. HighlightLayer.prototype._createMergeEffect = function () {
  91857. // Effect
  91858. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  91859. };
  91860. /**
  91861. * Creates the render target textures and post processes used in the highlight layer.
  91862. */
  91863. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  91864. var _this = this;
  91865. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  91866. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  91867. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  91868. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  91869. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  91870. width: blurTextureWidth,
  91871. height: blurTextureHeight
  91872. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  91873. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91874. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91875. this._blurTexture.anisotropicFilteringLevel = 16;
  91876. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  91877. this._blurTexture.renderParticles = false;
  91878. this._blurTexture.ignoreCameraViewport = true;
  91879. this._textures = [this._blurTexture];
  91880. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  91881. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  91882. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  91883. effect.setTexture("textureSampler", _this._mainTexture);
  91884. });
  91885. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  91886. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  91887. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  91888. });
  91889. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  91890. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  91891. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  91892. });
  91893. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  91894. }
  91895. else {
  91896. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  91897. width: blurTextureWidth,
  91898. height: blurTextureHeight
  91899. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  91900. this._horizontalBlurPostprocess.width = blurTextureWidth;
  91901. this._horizontalBlurPostprocess.height = blurTextureHeight;
  91902. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  91903. effect.setTexture("textureSampler", _this._mainTexture);
  91904. });
  91905. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  91906. width: blurTextureWidth,
  91907. height: blurTextureHeight
  91908. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  91909. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  91910. }
  91911. this._mainTexture.onAfterUnbindObservable.add(function () {
  91912. _this.onBeforeBlurObservable.notifyObservers(_this);
  91913. var internalTexture = _this._blurTexture.getInternalTexture();
  91914. if (internalTexture) {
  91915. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  91916. }
  91917. _this.onAfterBlurObservable.notifyObservers(_this);
  91918. });
  91919. // Prevent autoClear.
  91920. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  91921. };
  91922. /**
  91923. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  91924. */
  91925. HighlightLayer.prototype.needStencil = function () {
  91926. return true;
  91927. };
  91928. /**
  91929. * Checks for the readiness of the element composing the layer.
  91930. * @param subMesh the mesh to check for
  91931. * @param useInstances specify wether or not to use instances to render the mesh
  91932. * @param emissiveTexture the associated emissive texture used to generate the glow
  91933. * @return true if ready otherwise, false
  91934. */
  91935. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  91936. var material = subMesh.getMaterial();
  91937. var mesh = subMesh.getRenderingMesh();
  91938. if (!material || !mesh || !this._meshes) {
  91939. return false;
  91940. }
  91941. var emissiveTexture = null;
  91942. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  91943. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  91944. emissiveTexture = material.emissiveTexture;
  91945. }
  91946. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  91947. };
  91948. /**
  91949. * Implementation specific of rendering the generating effect on the main canvas.
  91950. * @param effect The effect used to render through
  91951. */
  91952. HighlightLayer.prototype._internalRender = function (effect) {
  91953. // Texture
  91954. effect.setTexture("textureSampler", this._blurTexture);
  91955. // Cache
  91956. var engine = this._engine;
  91957. var previousStencilBuffer = engine.getStencilBuffer();
  91958. var previousStencilFunction = engine.getStencilFunction();
  91959. var previousStencilMask = engine.getStencilMask();
  91960. var previousStencilOperationPass = engine.getStencilOperationPass();
  91961. var previousStencilOperationFail = engine.getStencilOperationFail();
  91962. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  91963. var previousStencilReference = engine.getStencilFunctionReference();
  91964. // Stencil operations
  91965. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  91966. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  91967. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  91968. // Draw order
  91969. engine.setStencilMask(0x00);
  91970. engine.setStencilBuffer(true);
  91971. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  91972. // 2 passes inner outer
  91973. if (this.outerGlow) {
  91974. effect.setFloat("offset", 0);
  91975. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  91976. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  91977. }
  91978. if (this.innerGlow) {
  91979. effect.setFloat("offset", 1);
  91980. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  91981. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  91982. }
  91983. // Restore Cache
  91984. engine.setStencilFunction(previousStencilFunction);
  91985. engine.setStencilMask(previousStencilMask);
  91986. engine.setStencilBuffer(previousStencilBuffer);
  91987. engine.setStencilOperationPass(previousStencilOperationPass);
  91988. engine.setStencilOperationFail(previousStencilOperationFail);
  91989. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  91990. engine.setStencilFunctionReference(previousStencilReference);
  91991. };
  91992. /**
  91993. * Returns true if the layer contains information to display, otherwise false.
  91994. */
  91995. HighlightLayer.prototype.shouldRender = function () {
  91996. if (_super.prototype.shouldRender.call(this)) {
  91997. return this._meshes ? true : false;
  91998. }
  91999. return false;
  92000. };
  92001. /**
  92002. * Returns true if the mesh should render, otherwise false.
  92003. * @param mesh The mesh to render
  92004. * @returns true if it should render otherwise false
  92005. */
  92006. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  92007. // Excluded Mesh
  92008. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  92009. return false;
  92010. }
  92011. ;
  92012. return true;
  92013. };
  92014. /**
  92015. * Sets the required values for both the emissive texture and and the main color.
  92016. */
  92017. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  92018. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  92019. if (highlightLayerMesh) {
  92020. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  92021. }
  92022. else {
  92023. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  92024. }
  92025. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  92026. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  92027. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  92028. }
  92029. else {
  92030. this._emissiveTextureAndColor.texture = null;
  92031. }
  92032. };
  92033. /**
  92034. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  92035. * @param mesh The mesh to exclude from the highlight layer
  92036. */
  92037. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  92038. if (!this._excludedMeshes) {
  92039. return;
  92040. }
  92041. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  92042. if (!meshExcluded) {
  92043. this._excludedMeshes[mesh.uniqueId] = {
  92044. mesh: mesh,
  92045. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  92046. mesh.getEngine().setStencilBuffer(false);
  92047. }),
  92048. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  92049. mesh.getEngine().setStencilBuffer(true);
  92050. }),
  92051. };
  92052. }
  92053. };
  92054. /**
  92055. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  92056. * @param mesh The mesh to highlight
  92057. */
  92058. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  92059. if (!this._excludedMeshes) {
  92060. return;
  92061. }
  92062. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  92063. if (meshExcluded) {
  92064. if (meshExcluded.beforeRender) {
  92065. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  92066. }
  92067. if (meshExcluded.afterRender) {
  92068. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  92069. }
  92070. }
  92071. this._excludedMeshes[mesh.uniqueId] = null;
  92072. };
  92073. /**
  92074. * Determine if a given mesh will be highlighted by the current HighlightLayer
  92075. * @param mesh mesh to test
  92076. * @returns true if the mesh will be highlighted by the current HighlightLayer
  92077. */
  92078. HighlightLayer.prototype.hasMesh = function (mesh) {
  92079. if (!this._meshes) {
  92080. return false;
  92081. }
  92082. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  92083. };
  92084. /**
  92085. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  92086. * @param mesh The mesh to highlight
  92087. * @param color The color of the highlight
  92088. * @param glowEmissiveOnly Extract the glow from the emissive texture
  92089. */
  92090. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  92091. var _this = this;
  92092. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  92093. if (!this._meshes) {
  92094. return;
  92095. }
  92096. var meshHighlight = this._meshes[mesh.uniqueId];
  92097. if (meshHighlight) {
  92098. meshHighlight.color = color;
  92099. }
  92100. else {
  92101. this._meshes[mesh.uniqueId] = {
  92102. mesh: mesh,
  92103. color: color,
  92104. // Lambda required for capture due to Observable this context
  92105. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  92106. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  92107. _this._defaultStencilReference(mesh);
  92108. }
  92109. else {
  92110. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  92111. }
  92112. }),
  92113. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  92114. glowEmissiveOnly: glowEmissiveOnly
  92115. };
  92116. }
  92117. this._shouldRender = true;
  92118. };
  92119. /**
  92120. * Remove a mesh from the highlight layer in order to make it stop glowing.
  92121. * @param mesh The mesh to highlight
  92122. */
  92123. HighlightLayer.prototype.removeMesh = function (mesh) {
  92124. if (!this._meshes) {
  92125. return;
  92126. }
  92127. var meshHighlight = this._meshes[mesh.uniqueId];
  92128. if (meshHighlight) {
  92129. if (meshHighlight.observerHighlight) {
  92130. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  92131. }
  92132. if (meshHighlight.observerDefault) {
  92133. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  92134. }
  92135. delete this._meshes[mesh.uniqueId];
  92136. }
  92137. this._shouldRender = false;
  92138. for (var meshHighlightToCheck in this._meshes) {
  92139. if (this._meshes[meshHighlightToCheck]) {
  92140. this._shouldRender = true;
  92141. break;
  92142. }
  92143. }
  92144. };
  92145. /**
  92146. * Force the stencil to the normal expected value for none glowing parts
  92147. */
  92148. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  92149. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  92150. };
  92151. /**
  92152. * Free any resources and references associated to a mesh.
  92153. * Internal use
  92154. * @param mesh The mesh to free.
  92155. */
  92156. HighlightLayer.prototype._disposeMesh = function (mesh) {
  92157. this.removeMesh(mesh);
  92158. this.removeExcludedMesh(mesh);
  92159. };
  92160. /**
  92161. * Dispose the highlight layer and free resources.
  92162. */
  92163. HighlightLayer.prototype.dispose = function () {
  92164. if (this._meshes) {
  92165. // Clean mesh references
  92166. for (var id in this._meshes) {
  92167. var meshHighlight = this._meshes[id];
  92168. if (meshHighlight && meshHighlight.mesh) {
  92169. if (meshHighlight.observerHighlight) {
  92170. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  92171. }
  92172. if (meshHighlight.observerDefault) {
  92173. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  92174. }
  92175. }
  92176. }
  92177. this._meshes = null;
  92178. }
  92179. if (this._excludedMeshes) {
  92180. for (var id in this._excludedMeshes) {
  92181. var meshHighlight = this._excludedMeshes[id];
  92182. if (meshHighlight) {
  92183. if (meshHighlight.beforeRender) {
  92184. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  92185. }
  92186. if (meshHighlight.afterRender) {
  92187. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  92188. }
  92189. }
  92190. }
  92191. this._excludedMeshes = null;
  92192. }
  92193. _super.prototype.dispose.call(this);
  92194. };
  92195. /**
  92196. * Gets the class name of the effect layer
  92197. * @returns the string with the class name of the effect layer
  92198. */
  92199. HighlightLayer.prototype.getClassName = function () {
  92200. return "HighlightLayer";
  92201. };
  92202. /**
  92203. * Serializes this Highlight layer
  92204. * @returns a serialized Highlight layer object
  92205. */
  92206. HighlightLayer.prototype.serialize = function () {
  92207. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  92208. serializationObject.customType = "BABYLON.HighlightLayer";
  92209. // Highlighted meshes
  92210. serializationObject.meshes = [];
  92211. if (this._meshes) {
  92212. for (var m in this._meshes) {
  92213. var mesh = this._meshes[m];
  92214. if (mesh) {
  92215. serializationObject.meshes.push({
  92216. glowEmissiveOnly: mesh.glowEmissiveOnly,
  92217. color: mesh.color.asArray(),
  92218. meshId: mesh.mesh.id
  92219. });
  92220. }
  92221. }
  92222. }
  92223. // Excluded meshes
  92224. serializationObject.excludedMeshes = [];
  92225. if (this._excludedMeshes) {
  92226. for (var e in this._excludedMeshes) {
  92227. var excludedMesh = this._excludedMeshes[e];
  92228. if (excludedMesh) {
  92229. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  92230. }
  92231. }
  92232. }
  92233. return serializationObject;
  92234. };
  92235. /**
  92236. * Creates a Highlight layer from parsed Highlight layer data
  92237. * @param parsedHightlightLayer defines the Highlight layer data
  92238. * @param scene defines the current scene
  92239. * @param rootUrl defines the root URL containing the Highlight layer information
  92240. * @returns a parsed Highlight layer
  92241. */
  92242. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  92243. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  92244. var index;
  92245. // Excluded meshes
  92246. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  92247. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  92248. if (mesh) {
  92249. hl.addExcludedMesh(mesh);
  92250. }
  92251. }
  92252. // Included meshes
  92253. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  92254. var highlightedMesh = parsedHightlightLayer.meshes[index];
  92255. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  92256. if (mesh) {
  92257. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  92258. }
  92259. }
  92260. return hl;
  92261. };
  92262. /**
  92263. * Effect Name of the highlight layer.
  92264. */
  92265. HighlightLayer.EffectName = "HighlightLayer";
  92266. /**
  92267. * The neutral color used during the preparation of the glow effect.
  92268. * This is black by default as the blend operation is a blend operation.
  92269. */
  92270. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  92271. /**
  92272. * Stencil value used for glowing meshes.
  92273. */
  92274. HighlightLayer.GlowingMeshStencilReference = 0x02;
  92275. /**
  92276. * Stencil value used for the other meshes in the scene.
  92277. */
  92278. HighlightLayer.NormalMeshStencilReference = 0x01;
  92279. __decorate([
  92280. BABYLON.serialize()
  92281. ], HighlightLayer.prototype, "innerGlow", void 0);
  92282. __decorate([
  92283. BABYLON.serialize()
  92284. ], HighlightLayer.prototype, "outerGlow", void 0);
  92285. __decorate([
  92286. BABYLON.serialize()
  92287. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  92288. __decorate([
  92289. BABYLON.serialize()
  92290. ], HighlightLayer.prototype, "blurVerticalSize", null);
  92291. __decorate([
  92292. BABYLON.serialize("options")
  92293. ], HighlightLayer.prototype, "_options", void 0);
  92294. return HighlightLayer;
  92295. }(BABYLON.EffectLayer));
  92296. BABYLON.HighlightLayer = HighlightLayer;
  92297. })(BABYLON || (BABYLON = {}));
  92298. //# sourceMappingURL=babylon.highlightLayer.js.map
  92299. var BABYLON;
  92300. (function (BABYLON) {
  92301. /**
  92302. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  92303. *
  92304. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  92305. * glowy meshes to your scene.
  92306. *
  92307. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  92308. */
  92309. var GlowLayer = /** @class */ (function (_super) {
  92310. __extends(GlowLayer, _super);
  92311. /**
  92312. * Instantiates a new glow Layer and references it to the scene.
  92313. * @param name The name of the layer
  92314. * @param scene The scene to use the layer in
  92315. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  92316. */
  92317. function GlowLayer(name, scene, options) {
  92318. var _this = _super.call(this, name, scene) || this;
  92319. _this._intensity = 1.0;
  92320. _this._includedOnlyMeshes = [];
  92321. _this._excludedMeshes = [];
  92322. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  92323. // Adapt options
  92324. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  92325. // Initialize the layer
  92326. _this._init({
  92327. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  92328. camera: _this._options.camera,
  92329. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  92330. mainTextureRatio: _this._options.mainTextureRatio
  92331. });
  92332. return _this;
  92333. }
  92334. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  92335. /**
  92336. * Gets the kernel size of the blur.
  92337. */
  92338. get: function () {
  92339. return this._horizontalBlurPostprocess1.kernel;
  92340. },
  92341. /**
  92342. * Sets the kernel size of the blur.
  92343. */
  92344. set: function (value) {
  92345. this._horizontalBlurPostprocess1.kernel = value;
  92346. this._verticalBlurPostprocess1.kernel = value;
  92347. this._horizontalBlurPostprocess2.kernel = value;
  92348. this._verticalBlurPostprocess2.kernel = value;
  92349. },
  92350. enumerable: true,
  92351. configurable: true
  92352. });
  92353. Object.defineProperty(GlowLayer.prototype, "intensity", {
  92354. /**
  92355. * Gets the glow intensity.
  92356. */
  92357. get: function () {
  92358. return this._intensity;
  92359. },
  92360. /**
  92361. * Sets the glow intensity.
  92362. */
  92363. set: function (value) {
  92364. this._intensity = value;
  92365. },
  92366. enumerable: true,
  92367. configurable: true
  92368. });
  92369. /**
  92370. * Get the effect name of the layer.
  92371. * @return The effect name
  92372. */
  92373. GlowLayer.prototype.getEffectName = function () {
  92374. return GlowLayer.EffectName;
  92375. };
  92376. /**
  92377. * Create the merge effect. This is the shader use to blit the information back
  92378. * to the main canvas at the end of the scene rendering.
  92379. */
  92380. GlowLayer.prototype._createMergeEffect = function () {
  92381. // Effect
  92382. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  92383. };
  92384. /**
  92385. * Creates the render target textures and post processes used in the glow layer.
  92386. */
  92387. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  92388. var _this = this;
  92389. var blurTextureWidth = this._mainTextureDesiredSize.width;
  92390. var blurTextureHeight = this._mainTextureDesiredSize.height;
  92391. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  92392. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  92393. var textureType = 0;
  92394. if (this._engine.getCaps().textureHalfFloatRender) {
  92395. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  92396. }
  92397. else {
  92398. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  92399. }
  92400. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  92401. width: blurTextureWidth,
  92402. height: blurTextureHeight
  92403. }, this._scene, false, true, textureType);
  92404. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92405. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92406. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  92407. this._blurTexture1.renderParticles = false;
  92408. this._blurTexture1.ignoreCameraViewport = true;
  92409. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  92410. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  92411. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  92412. width: blurTextureWidth2,
  92413. height: blurTextureHeight2
  92414. }, this._scene, false, true, textureType);
  92415. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92416. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92417. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  92418. this._blurTexture2.renderParticles = false;
  92419. this._blurTexture2.ignoreCameraViewport = true;
  92420. this._textures = [this._blurTexture1, this._blurTexture2];
  92421. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  92422. width: blurTextureWidth,
  92423. height: blurTextureHeight
  92424. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  92425. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  92426. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  92427. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  92428. effect.setTexture("textureSampler", _this._mainTexture);
  92429. });
  92430. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  92431. width: blurTextureWidth,
  92432. height: blurTextureHeight
  92433. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  92434. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  92435. width: blurTextureWidth2,
  92436. height: blurTextureHeight2
  92437. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  92438. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  92439. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  92440. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  92441. effect.setTexture("textureSampler", _this._blurTexture1);
  92442. });
  92443. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  92444. width: blurTextureWidth2,
  92445. height: blurTextureHeight2
  92446. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  92447. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  92448. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  92449. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  92450. this._mainTexture.samples = this._options.mainTextureSamples;
  92451. this._mainTexture.onAfterUnbindObservable.add(function () {
  92452. var internalTexture = _this._blurTexture1.getInternalTexture();
  92453. if (internalTexture) {
  92454. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  92455. internalTexture = _this._blurTexture2.getInternalTexture();
  92456. if (internalTexture) {
  92457. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  92458. }
  92459. }
  92460. });
  92461. // Prevent autoClear.
  92462. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  92463. };
  92464. /**
  92465. * Checks for the readiness of the element composing the layer.
  92466. * @param subMesh the mesh to check for
  92467. * @param useInstances specify wether or not to use instances to render the mesh
  92468. * @param emissiveTexture the associated emissive texture used to generate the glow
  92469. * @return true if ready otherwise, false
  92470. */
  92471. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  92472. var material = subMesh.getMaterial();
  92473. var mesh = subMesh.getRenderingMesh();
  92474. if (!material || !mesh) {
  92475. return false;
  92476. }
  92477. var emissiveTexture = material.emissiveTexture;
  92478. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  92479. };
  92480. /**
  92481. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  92482. */
  92483. GlowLayer.prototype.needStencil = function () {
  92484. return false;
  92485. };
  92486. /**
  92487. * Implementation specific of rendering the generating effect on the main canvas.
  92488. * @param effect The effect used to render through
  92489. */
  92490. GlowLayer.prototype._internalRender = function (effect) {
  92491. // Texture
  92492. effect.setTexture("textureSampler", this._blurTexture1);
  92493. effect.setTexture("textureSampler2", this._blurTexture2);
  92494. effect.setFloat("offset", this._intensity);
  92495. // Cache
  92496. var engine = this._engine;
  92497. var previousStencilBuffer = engine.getStencilBuffer();
  92498. // Draw order
  92499. engine.setStencilBuffer(false);
  92500. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  92501. // Draw order
  92502. engine.setStencilBuffer(previousStencilBuffer);
  92503. };
  92504. /**
  92505. * Sets the required values for both the emissive texture and and the main color.
  92506. */
  92507. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  92508. var textureLevel = 1.0;
  92509. if (this.customEmissiveTextureSelector) {
  92510. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  92511. }
  92512. else {
  92513. if (material) {
  92514. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  92515. if (this._emissiveTextureAndColor.texture) {
  92516. textureLevel = this._emissiveTextureAndColor.texture.level;
  92517. }
  92518. }
  92519. else {
  92520. this._emissiveTextureAndColor.texture = null;
  92521. }
  92522. }
  92523. if (this.customEmissiveColorSelector) {
  92524. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  92525. }
  92526. else {
  92527. if (material.emissiveColor) {
  92528. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  92529. }
  92530. else {
  92531. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  92532. }
  92533. }
  92534. };
  92535. /**
  92536. * Returns true if the mesh should render, otherwise false.
  92537. * @param mesh The mesh to render
  92538. * @returns true if it should render otherwise false
  92539. */
  92540. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  92541. return this.hasMesh(mesh);
  92542. };
  92543. /**
  92544. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  92545. * @param mesh The mesh to exclude from the glow layer
  92546. */
  92547. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  92548. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  92549. this._excludedMeshes.push(mesh.uniqueId);
  92550. }
  92551. };
  92552. /**
  92553. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  92554. * @param mesh The mesh to remove
  92555. */
  92556. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  92557. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  92558. if (index !== -1) {
  92559. this._excludedMeshes.splice(index, 1);
  92560. }
  92561. };
  92562. /**
  92563. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  92564. * @param mesh The mesh to include in the glow layer
  92565. */
  92566. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  92567. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  92568. this._includedOnlyMeshes.push(mesh.uniqueId);
  92569. }
  92570. };
  92571. /**
  92572. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  92573. * @param mesh The mesh to remove
  92574. */
  92575. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  92576. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  92577. if (index !== -1) {
  92578. this._includedOnlyMeshes.splice(index, 1);
  92579. }
  92580. };
  92581. /**
  92582. * Determine if a given mesh will be used in the glow layer
  92583. * @param mesh The mesh to test
  92584. * @returns true if the mesh will be highlighted by the current glow layer
  92585. */
  92586. GlowLayer.prototype.hasMesh = function (mesh) {
  92587. // Included Mesh
  92588. if (this._includedOnlyMeshes.length) {
  92589. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  92590. }
  92591. ;
  92592. // Excluded Mesh
  92593. if (this._excludedMeshes.length) {
  92594. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  92595. }
  92596. ;
  92597. return true;
  92598. };
  92599. /**
  92600. * Free any resources and references associated to a mesh.
  92601. * Internal use
  92602. * @param mesh The mesh to free.
  92603. */
  92604. GlowLayer.prototype._disposeMesh = function (mesh) {
  92605. this.removeIncludedOnlyMesh(mesh);
  92606. this.removeExcludedMesh(mesh);
  92607. };
  92608. /**
  92609. * Gets the class name of the effect layer
  92610. * @returns the string with the class name of the effect layer
  92611. */
  92612. GlowLayer.prototype.getClassName = function () {
  92613. return "GlowLayer";
  92614. };
  92615. /**
  92616. * Serializes this glow layer
  92617. * @returns a serialized glow layer object
  92618. */
  92619. GlowLayer.prototype.serialize = function () {
  92620. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  92621. serializationObject.customType = "BABYLON.GlowLayer";
  92622. var index;
  92623. // Included meshes
  92624. serializationObject.includedMeshes = [];
  92625. if (this._includedOnlyMeshes.length) {
  92626. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  92627. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  92628. if (mesh) {
  92629. serializationObject.includedMeshes.push(mesh.id);
  92630. }
  92631. }
  92632. }
  92633. // Excluded meshes
  92634. serializationObject.excludedMeshes = [];
  92635. if (this._excludedMeshes.length) {
  92636. for (index = 0; index < this._excludedMeshes.length; index++) {
  92637. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  92638. if (mesh) {
  92639. serializationObject.excludedMeshes.push(mesh.id);
  92640. }
  92641. }
  92642. }
  92643. return serializationObject;
  92644. };
  92645. /**
  92646. * Creates a Glow Layer from parsed glow layer data
  92647. * @param parsedGlowLayer defines glow layer data
  92648. * @param scene defines the current scene
  92649. * @param rootUrl defines the root URL containing the glow layer information
  92650. * @returns a parsed Glow Layer
  92651. */
  92652. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  92653. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  92654. var index;
  92655. // Excluded meshes
  92656. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  92657. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  92658. if (mesh) {
  92659. gl.addExcludedMesh(mesh);
  92660. }
  92661. }
  92662. // Included meshes
  92663. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  92664. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  92665. if (mesh) {
  92666. gl.addIncludedOnlyMesh(mesh);
  92667. }
  92668. }
  92669. return gl;
  92670. };
  92671. /**
  92672. * Effect Name of the layer.
  92673. */
  92674. GlowLayer.EffectName = "GlowLayer";
  92675. /**
  92676. * The default blur kernel size used for the glow.
  92677. */
  92678. GlowLayer.DefaultBlurKernelSize = 32;
  92679. /**
  92680. * The default texture size ratio used for the glow.
  92681. */
  92682. GlowLayer.DefaultTextureRatio = 0.5;
  92683. __decorate([
  92684. BABYLON.serialize()
  92685. ], GlowLayer.prototype, "blurKernelSize", null);
  92686. __decorate([
  92687. BABYLON.serialize()
  92688. ], GlowLayer.prototype, "intensity", null);
  92689. __decorate([
  92690. BABYLON.serialize("options")
  92691. ], GlowLayer.prototype, "_options", void 0);
  92692. return GlowLayer;
  92693. }(BABYLON.EffectLayer));
  92694. BABYLON.GlowLayer = GlowLayer;
  92695. })(BABYLON || (BABYLON = {}));
  92696. //# sourceMappingURL=babylon.glowLayer.js.map
  92697. var BABYLON;
  92698. (function (BABYLON) {
  92699. /**
  92700. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  92701. */
  92702. var AssetTaskState;
  92703. (function (AssetTaskState) {
  92704. /**
  92705. * Initialization
  92706. */
  92707. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  92708. /**
  92709. * Running
  92710. */
  92711. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  92712. /**
  92713. * Done
  92714. */
  92715. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  92716. /**
  92717. * Error
  92718. */
  92719. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  92720. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  92721. /**
  92722. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  92723. */
  92724. var AbstractAssetTask = /** @class */ (function () {
  92725. /**
  92726. * Creates a new {BABYLON.AssetsManager}
  92727. * @param name defines the name of the task
  92728. */
  92729. function AbstractAssetTask(
  92730. /**
  92731. * Task name
  92732. */ name) {
  92733. this.name = name;
  92734. this._isCompleted = false;
  92735. this._taskState = AssetTaskState.INIT;
  92736. }
  92737. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  92738. /**
  92739. * Get if the task is completed
  92740. */
  92741. get: function () {
  92742. return this._isCompleted;
  92743. },
  92744. enumerable: true,
  92745. configurable: true
  92746. });
  92747. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  92748. /**
  92749. * Gets the current state of the task
  92750. */
  92751. get: function () {
  92752. return this._taskState;
  92753. },
  92754. enumerable: true,
  92755. configurable: true
  92756. });
  92757. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  92758. /**
  92759. * Gets the current error object (if task is in error)
  92760. */
  92761. get: function () {
  92762. return this._errorObject;
  92763. },
  92764. enumerable: true,
  92765. configurable: true
  92766. });
  92767. /**
  92768. * Internal only
  92769. * @hidden
  92770. */
  92771. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  92772. if (this._errorObject) {
  92773. return;
  92774. }
  92775. this._errorObject = {
  92776. message: message,
  92777. exception: exception
  92778. };
  92779. };
  92780. /**
  92781. * Execute the current task
  92782. * @param scene defines the scene where you want your assets to be loaded
  92783. * @param onSuccess is a callback called when the task is successfully executed
  92784. * @param onError is a callback called if an error occurs
  92785. */
  92786. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  92787. var _this = this;
  92788. this._taskState = AssetTaskState.RUNNING;
  92789. this.runTask(scene, function () {
  92790. _this.onDoneCallback(onSuccess, onError);
  92791. }, function (msg, exception) {
  92792. _this.onErrorCallback(onError, msg, exception);
  92793. });
  92794. };
  92795. /**
  92796. * Execute the current task
  92797. * @param scene defines the scene where you want your assets to be loaded
  92798. * @param onSuccess is a callback called when the task is successfully executed
  92799. * @param onError is a callback called if an error occurs
  92800. */
  92801. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92802. throw new Error("runTask is not implemented");
  92803. };
  92804. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  92805. this._taskState = AssetTaskState.ERROR;
  92806. this._errorObject = {
  92807. message: message,
  92808. exception: exception
  92809. };
  92810. if (this.onError) {
  92811. this.onError(this, message, exception);
  92812. }
  92813. onError();
  92814. };
  92815. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  92816. try {
  92817. this._taskState = AssetTaskState.DONE;
  92818. this._isCompleted = true;
  92819. if (this.onSuccess) {
  92820. this.onSuccess(this);
  92821. }
  92822. onSuccess();
  92823. }
  92824. catch (e) {
  92825. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  92826. }
  92827. };
  92828. return AbstractAssetTask;
  92829. }());
  92830. BABYLON.AbstractAssetTask = AbstractAssetTask;
  92831. /**
  92832. * Class used to share progress information about assets loading
  92833. */
  92834. var AssetsProgressEvent = /** @class */ (function () {
  92835. /**
  92836. * Creates a {BABYLON.AssetsProgressEvent}
  92837. * @param remainingCount defines the number of remaining tasks to process
  92838. * @param totalCount defines the total number of tasks
  92839. * @param task defines the task that was just processed
  92840. */
  92841. function AssetsProgressEvent(remainingCount, totalCount, task) {
  92842. this.remainingCount = remainingCount;
  92843. this.totalCount = totalCount;
  92844. this.task = task;
  92845. }
  92846. return AssetsProgressEvent;
  92847. }());
  92848. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  92849. /**
  92850. * Define a task used by {BABYLON.AssetsManager} to load meshes
  92851. */
  92852. var MeshAssetTask = /** @class */ (function (_super) {
  92853. __extends(MeshAssetTask, _super);
  92854. /**
  92855. * Creates a new {BABYLON.MeshAssetTask}
  92856. * @param name defines the name of the task
  92857. * @param meshesNames defines the list of mesh's names you want to load
  92858. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  92859. * @param sceneFilename defines the filename of the scene to load from
  92860. */
  92861. function MeshAssetTask(
  92862. /**
  92863. * Defines the name of the task
  92864. */
  92865. name,
  92866. /**
  92867. * Defines the list of mesh's names you want to load
  92868. */
  92869. meshesNames,
  92870. /**
  92871. * Defines the root url to use as a base to load your meshes and associated resources
  92872. */
  92873. rootUrl,
  92874. /**
  92875. * Defines the filename of the scene to load from
  92876. */
  92877. sceneFilename) {
  92878. var _this = _super.call(this, name) || this;
  92879. _this.name = name;
  92880. _this.meshesNames = meshesNames;
  92881. _this.rootUrl = rootUrl;
  92882. _this.sceneFilename = sceneFilename;
  92883. return _this;
  92884. }
  92885. /**
  92886. * Execute the current task
  92887. * @param scene defines the scene where you want your assets to be loaded
  92888. * @param onSuccess is a callback called when the task is successfully executed
  92889. * @param onError is a callback called if an error occurs
  92890. */
  92891. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92892. var _this = this;
  92893. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  92894. _this.loadedMeshes = meshes;
  92895. _this.loadedParticleSystems = particleSystems;
  92896. _this.loadedSkeletons = skeletons;
  92897. onSuccess();
  92898. }, null, function (scene, message, exception) {
  92899. onError(message, exception);
  92900. });
  92901. };
  92902. return MeshAssetTask;
  92903. }(AbstractAssetTask));
  92904. BABYLON.MeshAssetTask = MeshAssetTask;
  92905. /**
  92906. * Define a task used by {BABYLON.AssetsManager} to load text content
  92907. */
  92908. var TextFileAssetTask = /** @class */ (function (_super) {
  92909. __extends(TextFileAssetTask, _super);
  92910. /**
  92911. * Creates a new TextFileAssetTask object
  92912. * @param name defines the name of the task
  92913. * @param url defines the location of the file to load
  92914. */
  92915. function TextFileAssetTask(
  92916. /**
  92917. * Defines the name of the task
  92918. */
  92919. name,
  92920. /**
  92921. * Defines the location of the file to load
  92922. */
  92923. url) {
  92924. var _this = _super.call(this, name) || this;
  92925. _this.name = name;
  92926. _this.url = url;
  92927. return _this;
  92928. }
  92929. /**
  92930. * Execute the current task
  92931. * @param scene defines the scene where you want your assets to be loaded
  92932. * @param onSuccess is a callback called when the task is successfully executed
  92933. * @param onError is a callback called if an error occurs
  92934. */
  92935. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92936. var _this = this;
  92937. scene._loadFile(this.url, function (data) {
  92938. _this.text = data;
  92939. onSuccess();
  92940. }, undefined, false, false, function (request, exception) {
  92941. if (request) {
  92942. onError(request.status + " " + request.statusText, exception);
  92943. }
  92944. });
  92945. };
  92946. return TextFileAssetTask;
  92947. }(AbstractAssetTask));
  92948. BABYLON.TextFileAssetTask = TextFileAssetTask;
  92949. /**
  92950. * Define a task used by {BABYLON.AssetsManager} to load binary data
  92951. */
  92952. var BinaryFileAssetTask = /** @class */ (function (_super) {
  92953. __extends(BinaryFileAssetTask, _super);
  92954. /**
  92955. * Creates a new BinaryFileAssetTask object
  92956. * @param name defines the name of the new task
  92957. * @param url defines the location of the file to load
  92958. */
  92959. function BinaryFileAssetTask(
  92960. /**
  92961. * Defines the name of the task
  92962. */
  92963. name,
  92964. /**
  92965. * Defines the location of the file to load
  92966. */
  92967. url) {
  92968. var _this = _super.call(this, name) || this;
  92969. _this.name = name;
  92970. _this.url = url;
  92971. return _this;
  92972. }
  92973. /**
  92974. * Execute the current task
  92975. * @param scene defines the scene where you want your assets to be loaded
  92976. * @param onSuccess is a callback called when the task is successfully executed
  92977. * @param onError is a callback called if an error occurs
  92978. */
  92979. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92980. var _this = this;
  92981. scene._loadFile(this.url, function (data) {
  92982. _this.data = data;
  92983. onSuccess();
  92984. }, undefined, true, true, function (request, exception) {
  92985. if (request) {
  92986. onError(request.status + " " + request.statusText, exception);
  92987. }
  92988. });
  92989. };
  92990. return BinaryFileAssetTask;
  92991. }(AbstractAssetTask));
  92992. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  92993. /**
  92994. * Define a task used by {BABYLON.AssetsManager} to load images
  92995. */
  92996. var ImageAssetTask = /** @class */ (function (_super) {
  92997. __extends(ImageAssetTask, _super);
  92998. /**
  92999. * Creates a new ImageAssetTask
  93000. * @param name defines the name of the task
  93001. * @param url defines the location of the image to load
  93002. */
  93003. function ImageAssetTask(
  93004. /**
  93005. * Defines the name of the task
  93006. */
  93007. name,
  93008. /**
  93009. * Defines the location of the image to load
  93010. */
  93011. url) {
  93012. var _this = _super.call(this, name) || this;
  93013. _this.name = name;
  93014. _this.url = url;
  93015. return _this;
  93016. }
  93017. /**
  93018. * Execute the current task
  93019. * @param scene defines the scene where you want your assets to be loaded
  93020. * @param onSuccess is a callback called when the task is successfully executed
  93021. * @param onError is a callback called if an error occurs
  93022. */
  93023. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93024. var _this = this;
  93025. var img = new Image();
  93026. BABYLON.Tools.SetCorsBehavior(this.url, img);
  93027. img.onload = function () {
  93028. _this.image = img;
  93029. onSuccess();
  93030. };
  93031. img.onerror = function (err) {
  93032. onError("Error loading image", err);
  93033. };
  93034. img.src = this.url;
  93035. };
  93036. return ImageAssetTask;
  93037. }(AbstractAssetTask));
  93038. BABYLON.ImageAssetTask = ImageAssetTask;
  93039. /**
  93040. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  93041. */
  93042. var TextureAssetTask = /** @class */ (function (_super) {
  93043. __extends(TextureAssetTask, _super);
  93044. /**
  93045. * Creates a new TextureAssetTask object
  93046. * @param name defines the name of the task
  93047. * @param url defines the location of the file to load
  93048. * @param noMipmap defines if mipmap should not be generated (default is false)
  93049. * @param invertY defines if texture must be inverted on Y axis (default is false)
  93050. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  93051. */
  93052. function TextureAssetTask(
  93053. /**
  93054. * Defines the name of the task
  93055. */
  93056. name,
  93057. /**
  93058. * Defines the location of the file to load
  93059. */
  93060. url,
  93061. /**
  93062. * Defines if mipmap should not be generated (default is false)
  93063. */
  93064. noMipmap,
  93065. /**
  93066. * Defines if texture must be inverted on Y axis (default is false)
  93067. */
  93068. invertY,
  93069. /**
  93070. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  93071. */
  93072. samplingMode) {
  93073. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  93074. var _this = _super.call(this, name) || this;
  93075. _this.name = name;
  93076. _this.url = url;
  93077. _this.noMipmap = noMipmap;
  93078. _this.invertY = invertY;
  93079. _this.samplingMode = samplingMode;
  93080. return _this;
  93081. }
  93082. /**
  93083. * Execute the current task
  93084. * @param scene defines the scene where you want your assets to be loaded
  93085. * @param onSuccess is a callback called when the task is successfully executed
  93086. * @param onError is a callback called if an error occurs
  93087. */
  93088. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93089. var onload = function () {
  93090. onSuccess();
  93091. };
  93092. var onerror = function (message, exception) {
  93093. onError(message, exception);
  93094. };
  93095. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  93096. };
  93097. return TextureAssetTask;
  93098. }(AbstractAssetTask));
  93099. BABYLON.TextureAssetTask = TextureAssetTask;
  93100. /**
  93101. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  93102. */
  93103. var CubeTextureAssetTask = /** @class */ (function (_super) {
  93104. __extends(CubeTextureAssetTask, _super);
  93105. /**
  93106. * Creates a new CubeTextureAssetTask
  93107. * @param name defines the name of the task
  93108. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  93109. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  93110. * @param noMipmap defines if mipmaps should not be generated (default is false)
  93111. * @param files defines the explicit list of files (undefined by default)
  93112. */
  93113. function CubeTextureAssetTask(
  93114. /**
  93115. * Defines the name of the task
  93116. */
  93117. name,
  93118. /**
  93119. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  93120. */
  93121. url,
  93122. /**
  93123. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  93124. */
  93125. extensions,
  93126. /**
  93127. * Defines if mipmaps should not be generated (default is false)
  93128. */
  93129. noMipmap,
  93130. /**
  93131. * Defines the explicit list of files (undefined by default)
  93132. */
  93133. files) {
  93134. var _this = _super.call(this, name) || this;
  93135. _this.name = name;
  93136. _this.url = url;
  93137. _this.extensions = extensions;
  93138. _this.noMipmap = noMipmap;
  93139. _this.files = files;
  93140. return _this;
  93141. }
  93142. /**
  93143. * Execute the current task
  93144. * @param scene defines the scene where you want your assets to be loaded
  93145. * @param onSuccess is a callback called when the task is successfully executed
  93146. * @param onError is a callback called if an error occurs
  93147. */
  93148. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93149. var onload = function () {
  93150. onSuccess();
  93151. };
  93152. var onerror = function (message, exception) {
  93153. onError(message, exception);
  93154. };
  93155. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  93156. };
  93157. return CubeTextureAssetTask;
  93158. }(AbstractAssetTask));
  93159. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  93160. /**
  93161. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  93162. */
  93163. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  93164. __extends(HDRCubeTextureAssetTask, _super);
  93165. /**
  93166. * Creates a new HDRCubeTextureAssetTask object
  93167. * @param name defines the name of the task
  93168. * @param url defines the location of the file to load
  93169. * @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.
  93170. * @param noMipmap defines if mipmaps should not be generated (default is false)
  93171. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  93172. * @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)
  93173. * @param reserved Internal use only
  93174. */
  93175. function HDRCubeTextureAssetTask(
  93176. /**
  93177. * Defines the name of the task
  93178. */
  93179. name,
  93180. /**
  93181. * Defines the location of the file to load
  93182. */
  93183. url,
  93184. /**
  93185. * Defines the desired size (the more it increases the longer the generation will be)
  93186. */
  93187. size,
  93188. /**
  93189. * Defines if mipmaps should not be generated (default is false)
  93190. */
  93191. noMipmap,
  93192. /**
  93193. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  93194. */
  93195. generateHarmonics,
  93196. /**
  93197. * 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)
  93198. */
  93199. gammaSpace,
  93200. /**
  93201. * Internal Use Only
  93202. */
  93203. reserved) {
  93204. if (noMipmap === void 0) { noMipmap = false; }
  93205. if (generateHarmonics === void 0) { generateHarmonics = true; }
  93206. if (gammaSpace === void 0) { gammaSpace = false; }
  93207. if (reserved === void 0) { reserved = false; }
  93208. var _this = _super.call(this, name) || this;
  93209. _this.name = name;
  93210. _this.url = url;
  93211. _this.size = size;
  93212. _this.noMipmap = noMipmap;
  93213. _this.generateHarmonics = generateHarmonics;
  93214. _this.gammaSpace = gammaSpace;
  93215. _this.reserved = reserved;
  93216. return _this;
  93217. }
  93218. /**
  93219. * Execute the current task
  93220. * @param scene defines the scene where you want your assets to be loaded
  93221. * @param onSuccess is a callback called when the task is successfully executed
  93222. * @param onError is a callback called if an error occurs
  93223. */
  93224. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  93225. var onload = function () {
  93226. onSuccess();
  93227. };
  93228. var onerror = function (message, exception) {
  93229. onError(message, exception);
  93230. };
  93231. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  93232. };
  93233. return HDRCubeTextureAssetTask;
  93234. }(AbstractAssetTask));
  93235. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  93236. /**
  93237. * This class can be used to easily import assets into a scene
  93238. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  93239. */
  93240. var AssetsManager = /** @class */ (function () {
  93241. /**
  93242. * Creates a new AssetsManager
  93243. * @param scene defines the scene to work on
  93244. */
  93245. function AssetsManager(scene) {
  93246. this._isLoading = false;
  93247. this._tasks = new Array();
  93248. this._waitingTasksCount = 0;
  93249. this._totalTasksCount = 0;
  93250. /**
  93251. * Observable called when all tasks are processed
  93252. */
  93253. this.onTaskSuccessObservable = new BABYLON.Observable();
  93254. /**
  93255. * Observable called when a task had an error
  93256. */
  93257. this.onTaskErrorObservable = new BABYLON.Observable();
  93258. /**
  93259. * Observable called when a task is successful
  93260. */
  93261. this.onTasksDoneObservable = new BABYLON.Observable();
  93262. /**
  93263. * Observable called when a task is done (whatever the result is)
  93264. */
  93265. this.onProgressObservable = new BABYLON.Observable();
  93266. /**
  93267. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  93268. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  93269. */
  93270. this.useDefaultLoadingScreen = true;
  93271. this._scene = scene;
  93272. }
  93273. /**
  93274. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  93275. * @param taskName defines the name of the new task
  93276. * @param meshesNames defines the name of meshes to load
  93277. * @param rootUrl defines the root url to use to locate files
  93278. * @param sceneFilename defines the filename of the scene file
  93279. * @returns a new {BABYLON.MeshAssetTask} object
  93280. */
  93281. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  93282. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  93283. this._tasks.push(task);
  93284. return task;
  93285. };
  93286. /**
  93287. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  93288. * @param taskName defines the name of the new task
  93289. * @param url defines the url of the file to load
  93290. * @returns a new {BABYLON.TextFileAssetTask} object
  93291. */
  93292. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  93293. var task = new TextFileAssetTask(taskName, url);
  93294. this._tasks.push(task);
  93295. return task;
  93296. };
  93297. /**
  93298. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  93299. * @param taskName defines the name of the new task
  93300. * @param url defines the url of the file to load
  93301. * @returns a new {BABYLON.BinaryFileAssetTask} object
  93302. */
  93303. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  93304. var task = new BinaryFileAssetTask(taskName, url);
  93305. this._tasks.push(task);
  93306. return task;
  93307. };
  93308. /**
  93309. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  93310. * @param taskName defines the name of the new task
  93311. * @param url defines the url of the file to load
  93312. * @returns a new {BABYLON.ImageAssetTask} object
  93313. */
  93314. AssetsManager.prototype.addImageTask = function (taskName, url) {
  93315. var task = new ImageAssetTask(taskName, url);
  93316. this._tasks.push(task);
  93317. return task;
  93318. };
  93319. /**
  93320. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  93321. * @param taskName defines the name of the new task
  93322. * @param url defines the url of the file to load
  93323. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  93324. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  93325. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  93326. * @returns a new {BABYLON.TextureAssetTask} object
  93327. */
  93328. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  93329. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  93330. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  93331. this._tasks.push(task);
  93332. return task;
  93333. };
  93334. /**
  93335. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  93336. * @param taskName defines the name of the new task
  93337. * @param url defines the url of the file to load
  93338. * @param extensions defines the extension to use to load the cube map (can be null)
  93339. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  93340. * @param files defines the list of files to load (can be null)
  93341. * @returns a new {BABYLON.CubeTextureAssetTask} object
  93342. */
  93343. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  93344. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  93345. this._tasks.push(task);
  93346. return task;
  93347. };
  93348. /**
  93349. *
  93350. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  93351. * @param taskName defines the name of the new task
  93352. * @param url defines the url of the file to load
  93353. * @param size defines the size you want for the cubemap (can be null)
  93354. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  93355. * @param generateHarmonics defines if you want to automatically generate (true by default)
  93356. * @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)
  93357. * @param reserved Internal use only
  93358. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  93359. */
  93360. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  93361. if (noMipmap === void 0) { noMipmap = false; }
  93362. if (generateHarmonics === void 0) { generateHarmonics = true; }
  93363. if (gammaSpace === void 0) { gammaSpace = false; }
  93364. if (reserved === void 0) { reserved = false; }
  93365. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  93366. this._tasks.push(task);
  93367. return task;
  93368. };
  93369. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  93370. var _this = this;
  93371. this._waitingTasksCount--;
  93372. try {
  93373. if (task.taskState === AssetTaskState.DONE) {
  93374. // Let's remove successfull tasks
  93375. BABYLON.Tools.SetImmediate(function () {
  93376. var index = _this._tasks.indexOf(task);
  93377. if (index > -1) {
  93378. _this._tasks.splice(index, 1);
  93379. }
  93380. });
  93381. }
  93382. if (this.onProgress) {
  93383. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  93384. }
  93385. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  93386. }
  93387. catch (e) {
  93388. BABYLON.Tools.Error("Error running progress callbacks.");
  93389. console.log(e);
  93390. }
  93391. if (this._waitingTasksCount === 0) {
  93392. try {
  93393. if (this.onFinish) {
  93394. this.onFinish(this._tasks);
  93395. }
  93396. this.onTasksDoneObservable.notifyObservers(this._tasks);
  93397. }
  93398. catch (e) {
  93399. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  93400. console.log(e);
  93401. }
  93402. this._isLoading = false;
  93403. this._scene.getEngine().hideLoadingUI();
  93404. }
  93405. };
  93406. AssetsManager.prototype._runTask = function (task) {
  93407. var _this = this;
  93408. var done = function () {
  93409. try {
  93410. if (_this.onTaskSuccess) {
  93411. _this.onTaskSuccess(task);
  93412. }
  93413. _this.onTaskSuccessObservable.notifyObservers(task);
  93414. _this._decreaseWaitingTasksCount(task);
  93415. }
  93416. catch (e) {
  93417. error("Error executing task success callbacks", e);
  93418. }
  93419. };
  93420. var error = function (message, exception) {
  93421. task._setErrorObject(message, exception);
  93422. if (_this.onTaskError) {
  93423. _this.onTaskError(task);
  93424. }
  93425. _this.onTaskErrorObservable.notifyObservers(task);
  93426. _this._decreaseWaitingTasksCount(task);
  93427. };
  93428. task.run(this._scene, done, error);
  93429. };
  93430. /**
  93431. * Reset the {BABYLON.AssetsManager} and remove all tasks
  93432. * @return the current instance of the {BABYLON.AssetsManager}
  93433. */
  93434. AssetsManager.prototype.reset = function () {
  93435. this._isLoading = false;
  93436. this._tasks = new Array();
  93437. return this;
  93438. };
  93439. /**
  93440. * Start the loading process
  93441. * @return the current instance of the {BABYLON.AssetsManager}
  93442. */
  93443. AssetsManager.prototype.load = function () {
  93444. if (this._isLoading) {
  93445. return this;
  93446. }
  93447. this._isLoading = true;
  93448. this._waitingTasksCount = this._tasks.length;
  93449. this._totalTasksCount = this._tasks.length;
  93450. if (this._waitingTasksCount === 0) {
  93451. this._isLoading = false;
  93452. if (this.onFinish) {
  93453. this.onFinish(this._tasks);
  93454. }
  93455. this.onTasksDoneObservable.notifyObservers(this._tasks);
  93456. return this;
  93457. }
  93458. if (this.useDefaultLoadingScreen) {
  93459. this._scene.getEngine().displayLoadingUI();
  93460. }
  93461. for (var index = 0; index < this._tasks.length; index++) {
  93462. var task = this._tasks[index];
  93463. this._runTask(task);
  93464. }
  93465. return this;
  93466. };
  93467. return AssetsManager;
  93468. }());
  93469. BABYLON.AssetsManager = AssetsManager;
  93470. })(BABYLON || (BABYLON = {}));
  93471. //# sourceMappingURL=babylon.assetsManager.js.map
  93472. var BABYLON;
  93473. (function (BABYLON) {
  93474. var serializedGeometries = [];
  93475. var serializeGeometry = function (geometry, serializationGeometries) {
  93476. if (serializedGeometries[geometry.id]) {
  93477. return;
  93478. }
  93479. if (geometry.doNotSerialize) {
  93480. return;
  93481. }
  93482. if (geometry instanceof BABYLON.BoxGeometry) {
  93483. serializationGeometries.boxes.push(geometry.serialize());
  93484. }
  93485. else if (geometry instanceof BABYLON.SphereGeometry) {
  93486. serializationGeometries.spheres.push(geometry.serialize());
  93487. }
  93488. else if (geometry instanceof BABYLON.CylinderGeometry) {
  93489. serializationGeometries.cylinders.push(geometry.serialize());
  93490. }
  93491. else if (geometry instanceof BABYLON.TorusGeometry) {
  93492. serializationGeometries.toruses.push(geometry.serialize());
  93493. }
  93494. else if (geometry instanceof BABYLON.GroundGeometry) {
  93495. serializationGeometries.grounds.push(geometry.serialize());
  93496. }
  93497. else if (geometry instanceof BABYLON.Plane) {
  93498. serializationGeometries.planes.push(geometry.serialize());
  93499. }
  93500. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  93501. serializationGeometries.torusKnots.push(geometry.serialize());
  93502. }
  93503. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  93504. throw new Error("Unknown primitive type");
  93505. }
  93506. else {
  93507. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  93508. }
  93509. serializedGeometries[geometry.id] = true;
  93510. };
  93511. var serializeMesh = function (mesh, serializationScene) {
  93512. var serializationObject = {};
  93513. // Geometry
  93514. var geometry = mesh._geometry;
  93515. if (geometry) {
  93516. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  93517. // 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
  93518. serializeGeometry(geometry, serializationScene.geometries);
  93519. }
  93520. }
  93521. // Custom
  93522. if (mesh.serialize) {
  93523. mesh.serialize(serializationObject);
  93524. }
  93525. return serializationObject;
  93526. };
  93527. var finalizeSingleMesh = function (mesh, serializationObject) {
  93528. //only works if the mesh is already loaded
  93529. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  93530. //serialize material
  93531. if (mesh.material) {
  93532. if (mesh.material instanceof BABYLON.StandardMaterial) {
  93533. serializationObject.materials = serializationObject.materials || [];
  93534. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  93535. serializationObject.materials.push(mesh.material.serialize());
  93536. }
  93537. }
  93538. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  93539. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  93540. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  93541. serializationObject.multiMaterials.push(mesh.material.serialize());
  93542. }
  93543. }
  93544. }
  93545. //serialize geometry
  93546. var geometry = mesh._geometry;
  93547. if (geometry) {
  93548. if (!serializationObject.geometries) {
  93549. serializationObject.geometries = {};
  93550. serializationObject.geometries.boxes = [];
  93551. serializationObject.geometries.spheres = [];
  93552. serializationObject.geometries.cylinders = [];
  93553. serializationObject.geometries.toruses = [];
  93554. serializationObject.geometries.grounds = [];
  93555. serializationObject.geometries.planes = [];
  93556. serializationObject.geometries.torusKnots = [];
  93557. serializationObject.geometries.vertexData = [];
  93558. }
  93559. serializeGeometry(geometry, serializationObject.geometries);
  93560. }
  93561. // Skeletons
  93562. if (mesh.skeleton) {
  93563. serializationObject.skeletons = serializationObject.skeletons || [];
  93564. serializationObject.skeletons.push(mesh.skeleton.serialize());
  93565. }
  93566. //serialize the actual mesh
  93567. serializationObject.meshes = serializationObject.meshes || [];
  93568. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  93569. }
  93570. };
  93571. var SceneSerializer = /** @class */ (function () {
  93572. function SceneSerializer() {
  93573. }
  93574. SceneSerializer.ClearCache = function () {
  93575. serializedGeometries = [];
  93576. };
  93577. SceneSerializer.Serialize = function (scene) {
  93578. var serializationObject = {};
  93579. SceneSerializer.ClearCache();
  93580. // Scene
  93581. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  93582. serializationObject.autoClear = scene.autoClear;
  93583. serializationObject.clearColor = scene.clearColor.asArray();
  93584. serializationObject.ambientColor = scene.ambientColor.asArray();
  93585. serializationObject.gravity = scene.gravity.asArray();
  93586. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  93587. serializationObject.workerCollisions = scene.workerCollisions;
  93588. // Fog
  93589. if (scene.fogMode && scene.fogMode !== 0) {
  93590. serializationObject.fogMode = scene.fogMode;
  93591. serializationObject.fogColor = scene.fogColor.asArray();
  93592. serializationObject.fogStart = scene.fogStart;
  93593. serializationObject.fogEnd = scene.fogEnd;
  93594. serializationObject.fogDensity = scene.fogDensity;
  93595. }
  93596. //Physics
  93597. if (scene.isPhysicsEnabled()) {
  93598. var physicEngine = scene.getPhysicsEngine();
  93599. if (physicEngine) {
  93600. serializationObject.physicsEnabled = true;
  93601. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  93602. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  93603. }
  93604. }
  93605. // Metadata
  93606. if (scene.metadata) {
  93607. serializationObject.metadata = scene.metadata;
  93608. }
  93609. // Morph targets
  93610. serializationObject.morphTargetManagers = [];
  93611. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  93612. var abstractMesh = _a[_i];
  93613. var manager = abstractMesh.morphTargetManager;
  93614. if (manager) {
  93615. serializationObject.morphTargetManagers.push(manager.serialize());
  93616. }
  93617. }
  93618. // Lights
  93619. serializationObject.lights = [];
  93620. var index;
  93621. var light;
  93622. for (index = 0; index < scene.lights.length; index++) {
  93623. light = scene.lights[index];
  93624. if (!light.doNotSerialize) {
  93625. serializationObject.lights.push(light.serialize());
  93626. }
  93627. }
  93628. // Cameras
  93629. serializationObject.cameras = [];
  93630. for (index = 0; index < scene.cameras.length; index++) {
  93631. var camera = scene.cameras[index];
  93632. if (!camera.doNotSerialize) {
  93633. serializationObject.cameras.push(camera.serialize());
  93634. }
  93635. }
  93636. if (scene.activeCamera) {
  93637. serializationObject.activeCameraID = scene.activeCamera.id;
  93638. }
  93639. // Animations
  93640. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  93641. // Materials
  93642. serializationObject.materials = [];
  93643. serializationObject.multiMaterials = [];
  93644. var material;
  93645. for (index = 0; index < scene.materials.length; index++) {
  93646. material = scene.materials[index];
  93647. if (!material.doNotSerialize) {
  93648. serializationObject.materials.push(material.serialize());
  93649. }
  93650. }
  93651. // MultiMaterials
  93652. serializationObject.multiMaterials = [];
  93653. for (index = 0; index < scene.multiMaterials.length; index++) {
  93654. var multiMaterial = scene.multiMaterials[index];
  93655. serializationObject.multiMaterials.push(multiMaterial.serialize());
  93656. }
  93657. // Environment texture
  93658. if (scene.environmentTexture) {
  93659. serializationObject.environmentTexture = scene.environmentTexture.name;
  93660. }
  93661. // Skeletons
  93662. serializationObject.skeletons = [];
  93663. for (index = 0; index < scene.skeletons.length; index++) {
  93664. var skeleton = scene.skeletons[index];
  93665. if (!skeleton.doNotSerialize) {
  93666. serializationObject.skeletons.push(skeleton.serialize());
  93667. }
  93668. }
  93669. // Transform nodes
  93670. serializationObject.transformNodes = [];
  93671. for (index = 0; index < scene.transformNodes.length; index++) {
  93672. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  93673. }
  93674. // Geometries
  93675. serializationObject.geometries = {};
  93676. serializationObject.geometries.boxes = [];
  93677. serializationObject.geometries.spheres = [];
  93678. serializationObject.geometries.cylinders = [];
  93679. serializationObject.geometries.toruses = [];
  93680. serializationObject.geometries.grounds = [];
  93681. serializationObject.geometries.planes = [];
  93682. serializationObject.geometries.torusKnots = [];
  93683. serializationObject.geometries.vertexData = [];
  93684. serializedGeometries = [];
  93685. var geometries = scene.getGeometries();
  93686. for (index = 0; index < geometries.length; index++) {
  93687. var geometry = geometries[index];
  93688. if (geometry.isReady()) {
  93689. serializeGeometry(geometry, serializationObject.geometries);
  93690. }
  93691. }
  93692. // Meshes
  93693. serializationObject.meshes = [];
  93694. for (index = 0; index < scene.meshes.length; index++) {
  93695. var abstractMesh = scene.meshes[index];
  93696. if (abstractMesh instanceof BABYLON.Mesh) {
  93697. var mesh = abstractMesh;
  93698. if (!mesh.doNotSerialize) {
  93699. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  93700. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  93701. }
  93702. }
  93703. }
  93704. }
  93705. // Particles Systems
  93706. serializationObject.particleSystems = [];
  93707. for (index = 0; index < scene.particleSystems.length; index++) {
  93708. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  93709. }
  93710. // Lens flares
  93711. serializationObject.lensFlareSystems = [];
  93712. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  93713. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  93714. }
  93715. // Shadows
  93716. serializationObject.shadowGenerators = [];
  93717. for (index = 0; index < scene.lights.length; index++) {
  93718. light = scene.lights[index];
  93719. var shadowGenerator = light.getShadowGenerator();
  93720. if (shadowGenerator) {
  93721. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  93722. }
  93723. }
  93724. // Action Manager
  93725. if (scene.actionManager) {
  93726. serializationObject.actions = scene.actionManager.serialize("scene");
  93727. }
  93728. // Audio
  93729. serializationObject.sounds = [];
  93730. for (index = 0; index < scene.soundTracks.length; index++) {
  93731. var soundtrack = scene.soundTracks[index];
  93732. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  93733. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  93734. }
  93735. }
  93736. // Effect layers
  93737. serializationObject.effectLayers = [];
  93738. for (index = 0; index < scene.effectLayers.length; index++) {
  93739. var layer = scene.effectLayers[index];
  93740. if (layer.serialize) {
  93741. serializationObject.effectLayers.push(layer.serialize());
  93742. }
  93743. }
  93744. return serializationObject;
  93745. };
  93746. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  93747. if (withParents === void 0) { withParents = false; }
  93748. if (withChildren === void 0) { withChildren = false; }
  93749. var serializationObject = {};
  93750. SceneSerializer.ClearCache();
  93751. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  93752. if (withParents || withChildren) {
  93753. //deliberate for loop! not for each, appended should be processed as well.
  93754. for (var i = 0; i < toSerialize.length; ++i) {
  93755. if (withChildren) {
  93756. toSerialize[i].getDescendants().forEach(function (node) {
  93757. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  93758. toSerialize.push(node);
  93759. }
  93760. });
  93761. }
  93762. //make sure the array doesn't contain the object already
  93763. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  93764. toSerialize.push(toSerialize[i].parent);
  93765. }
  93766. }
  93767. }
  93768. toSerialize.forEach(function (mesh) {
  93769. finalizeSingleMesh(mesh, serializationObject);
  93770. });
  93771. return serializationObject;
  93772. };
  93773. return SceneSerializer;
  93774. }());
  93775. BABYLON.SceneSerializer = SceneSerializer;
  93776. })(BABYLON || (BABYLON = {}));
  93777. //# sourceMappingURL=babylon.sceneSerializer.js.map
  93778. var BABYLON;
  93779. (function (BABYLON) {
  93780. var ReflectionProbe = /** @class */ (function () {
  93781. function ReflectionProbe(name, size, scene, generateMipMaps) {
  93782. if (generateMipMaps === void 0) { generateMipMaps = true; }
  93783. var _this = this;
  93784. this.name = name;
  93785. this._viewMatrix = BABYLON.Matrix.Identity();
  93786. this._target = BABYLON.Vector3.Zero();
  93787. this._add = BABYLON.Vector3.Zero();
  93788. this._invertYAxis = false;
  93789. this.position = BABYLON.Vector3.Zero();
  93790. this._scene = scene;
  93791. this._scene.reflectionProbes.push(this);
  93792. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  93793. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  93794. switch (faceIndex) {
  93795. case 0:
  93796. _this._add.copyFromFloats(1, 0, 0);
  93797. break;
  93798. case 1:
  93799. _this._add.copyFromFloats(-1, 0, 0);
  93800. break;
  93801. case 2:
  93802. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  93803. break;
  93804. case 3:
  93805. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  93806. break;
  93807. case 4:
  93808. _this._add.copyFromFloats(0, 0, 1);
  93809. break;
  93810. case 5:
  93811. _this._add.copyFromFloats(0, 0, -1);
  93812. break;
  93813. }
  93814. if (_this._attachedMesh) {
  93815. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  93816. }
  93817. _this.position.addToRef(_this._add, _this._target);
  93818. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  93819. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  93820. scene._forcedViewPosition = _this.position;
  93821. });
  93822. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  93823. scene._forcedViewPosition = null;
  93824. scene.updateTransformMatrix(true);
  93825. });
  93826. if (scene.activeCamera) {
  93827. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  93828. }
  93829. }
  93830. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  93831. get: function () {
  93832. return this._renderTargetTexture.samples;
  93833. },
  93834. set: function (value) {
  93835. this._renderTargetTexture.samples = value;
  93836. },
  93837. enumerable: true,
  93838. configurable: true
  93839. });
  93840. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  93841. get: function () {
  93842. return this._renderTargetTexture.refreshRate;
  93843. },
  93844. set: function (value) {
  93845. this._renderTargetTexture.refreshRate = value;
  93846. },
  93847. enumerable: true,
  93848. configurable: true
  93849. });
  93850. ReflectionProbe.prototype.getScene = function () {
  93851. return this._scene;
  93852. };
  93853. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  93854. get: function () {
  93855. return this._renderTargetTexture;
  93856. },
  93857. enumerable: true,
  93858. configurable: true
  93859. });
  93860. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  93861. get: function () {
  93862. return this._renderTargetTexture.renderList;
  93863. },
  93864. enumerable: true,
  93865. configurable: true
  93866. });
  93867. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  93868. this._attachedMesh = mesh;
  93869. };
  93870. /**
  93871. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  93872. *
  93873. * @param renderingGroupId The rendering group id corresponding to its index
  93874. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  93875. */
  93876. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  93877. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  93878. };
  93879. ReflectionProbe.prototype.dispose = function () {
  93880. var index = this._scene.reflectionProbes.indexOf(this);
  93881. if (index !== -1) {
  93882. // Remove from the scene if found
  93883. this._scene.reflectionProbes.splice(index, 1);
  93884. }
  93885. if (this._renderTargetTexture) {
  93886. this._renderTargetTexture.dispose();
  93887. this._renderTargetTexture = null;
  93888. }
  93889. };
  93890. return ReflectionProbe;
  93891. }());
  93892. BABYLON.ReflectionProbe = ReflectionProbe;
  93893. })(BABYLON || (BABYLON = {}));
  93894. //# sourceMappingURL=babylon.reflectionProbe.js.map
  93895. var BABYLON;
  93896. (function (BABYLON) {
  93897. var Layer = /** @class */ (function () {
  93898. function Layer(name, imgUrl, scene, isBackground, color) {
  93899. this.name = name;
  93900. this.scale = new BABYLON.Vector2(1, 1);
  93901. this.offset = new BABYLON.Vector2(0, 0);
  93902. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  93903. this.layerMask = 0x0FFFFFFF;
  93904. this._vertexBuffers = {};
  93905. // Events
  93906. /**
  93907. * An event triggered when the layer is disposed.
  93908. */
  93909. this.onDisposeObservable = new BABYLON.Observable();
  93910. /**
  93911. * An event triggered before rendering the scene
  93912. */
  93913. this.onBeforeRenderObservable = new BABYLON.Observable();
  93914. /**
  93915. * An event triggered after rendering the scene
  93916. */
  93917. this.onAfterRenderObservable = new BABYLON.Observable();
  93918. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  93919. this.isBackground = isBackground === undefined ? true : isBackground;
  93920. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  93921. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  93922. this._scene.layers.push(this);
  93923. var engine = this._scene.getEngine();
  93924. // VBO
  93925. var vertices = [];
  93926. vertices.push(1, 1);
  93927. vertices.push(-1, 1);
  93928. vertices.push(-1, -1);
  93929. vertices.push(1, -1);
  93930. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  93931. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  93932. this._createIndexBuffer();
  93933. // Effects
  93934. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  93935. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  93936. }
  93937. Object.defineProperty(Layer.prototype, "onDispose", {
  93938. set: function (callback) {
  93939. if (this._onDisposeObserver) {
  93940. this.onDisposeObservable.remove(this._onDisposeObserver);
  93941. }
  93942. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  93943. },
  93944. enumerable: true,
  93945. configurable: true
  93946. });
  93947. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  93948. set: function (callback) {
  93949. if (this._onBeforeRenderObserver) {
  93950. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  93951. }
  93952. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  93953. },
  93954. enumerable: true,
  93955. configurable: true
  93956. });
  93957. Object.defineProperty(Layer.prototype, "onAfterRender", {
  93958. set: function (callback) {
  93959. if (this._onAfterRenderObserver) {
  93960. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  93961. }
  93962. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  93963. },
  93964. enumerable: true,
  93965. configurable: true
  93966. });
  93967. Layer.prototype._createIndexBuffer = function () {
  93968. var engine = this._scene.getEngine();
  93969. // Indices
  93970. var indices = [];
  93971. indices.push(0);
  93972. indices.push(1);
  93973. indices.push(2);
  93974. indices.push(0);
  93975. indices.push(2);
  93976. indices.push(3);
  93977. this._indexBuffer = engine.createIndexBuffer(indices);
  93978. };
  93979. Layer.prototype._rebuild = function () {
  93980. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  93981. if (vb) {
  93982. vb._rebuild();
  93983. }
  93984. this._createIndexBuffer();
  93985. };
  93986. Layer.prototype.render = function () {
  93987. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  93988. // Check
  93989. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  93990. return;
  93991. var engine = this._scene.getEngine();
  93992. this.onBeforeRenderObservable.notifyObservers(this);
  93993. // Render
  93994. engine.enableEffect(currentEffect);
  93995. engine.setState(false);
  93996. // Texture
  93997. currentEffect.setTexture("textureSampler", this.texture);
  93998. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  93999. // Color
  94000. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  94001. // Scale / offset
  94002. currentEffect.setVector2("offset", this.offset);
  94003. currentEffect.setVector2("scale", this.scale);
  94004. // VBOs
  94005. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  94006. // Draw order
  94007. if (!this.alphaTest) {
  94008. engine.setAlphaMode(this.alphaBlendingMode);
  94009. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  94010. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  94011. }
  94012. else {
  94013. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  94014. }
  94015. this.onAfterRenderObservable.notifyObservers(this);
  94016. };
  94017. Layer.prototype.dispose = function () {
  94018. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  94019. if (vertexBuffer) {
  94020. vertexBuffer.dispose();
  94021. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  94022. }
  94023. if (this._indexBuffer) {
  94024. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  94025. this._indexBuffer = null;
  94026. }
  94027. if (this.texture) {
  94028. this.texture.dispose();
  94029. this.texture = null;
  94030. }
  94031. // Remove from scene
  94032. var index = this._scene.layers.indexOf(this);
  94033. this._scene.layers.splice(index, 1);
  94034. // Callback
  94035. this.onDisposeObservable.notifyObservers(this);
  94036. this.onDisposeObservable.clear();
  94037. this.onAfterRenderObservable.clear();
  94038. this.onBeforeRenderObservable.clear();
  94039. };
  94040. return Layer;
  94041. }());
  94042. BABYLON.Layer = Layer;
  94043. })(BABYLON || (BABYLON = {}));
  94044. //# sourceMappingURL=babylon.layer.js.map
  94045. var BABYLON;
  94046. (function (BABYLON) {
  94047. var TextureTools = /** @class */ (function () {
  94048. function TextureTools() {
  94049. }
  94050. /**
  94051. * Uses the GPU to create a copy texture rescaled at a given size
  94052. * @param texture Texture to copy from
  94053. * @param width Desired width
  94054. * @param height Desired height
  94055. * @return Generated texture
  94056. */
  94057. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  94058. if (useBilinearMode === void 0) { useBilinearMode = true; }
  94059. var scene = texture.getScene();
  94060. var engine = scene.getEngine();
  94061. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  94062. rtt.wrapU = texture.wrapU;
  94063. rtt.wrapV = texture.wrapV;
  94064. rtt.uOffset = texture.uOffset;
  94065. rtt.vOffset = texture.vOffset;
  94066. rtt.uScale = texture.uScale;
  94067. rtt.vScale = texture.vScale;
  94068. rtt.uAng = texture.uAng;
  94069. rtt.vAng = texture.vAng;
  94070. rtt.wAng = texture.wAng;
  94071. rtt.coordinatesIndex = texture.coordinatesIndex;
  94072. rtt.level = texture.level;
  94073. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  94074. rtt._texture.isReady = false;
  94075. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94076. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94077. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  94078. passPostProcess.getEffect().executeWhenCompiled(function () {
  94079. passPostProcess.onApply = function (effect) {
  94080. effect.setTexture("textureSampler", texture);
  94081. };
  94082. var internalTexture = rtt.getInternalTexture();
  94083. if (internalTexture) {
  94084. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  94085. engine.unBindFramebuffer(internalTexture);
  94086. rtt.disposeFramebufferObjects();
  94087. passPostProcess.dispose();
  94088. internalTexture.isReady = true;
  94089. }
  94090. });
  94091. return rtt;
  94092. };
  94093. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  94094. if (!scene._environmentBRDFTexture) {
  94095. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  94096. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94097. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94098. scene._environmentBRDFTexture = texture;
  94099. }
  94100. return scene._environmentBRDFTexture;
  94101. };
  94102. 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=";
  94103. return TextureTools;
  94104. }());
  94105. BABYLON.TextureTools = TextureTools;
  94106. })(BABYLON || (BABYLON = {}));
  94107. //# sourceMappingURL=babylon.textureTools.js.map
  94108. var BABYLON;
  94109. (function (BABYLON) {
  94110. var FramingBehavior = /** @class */ (function () {
  94111. function FramingBehavior() {
  94112. this._mode = FramingBehavior.FitFrustumSidesMode;
  94113. this._radiusScale = 1.0;
  94114. this._positionScale = 0.5;
  94115. this._defaultElevation = 0.3;
  94116. this._elevationReturnTime = 1500;
  94117. this._elevationReturnWaitTime = 1000;
  94118. this._zoomStopsAnimation = false;
  94119. this._framingTime = 1500;
  94120. this._isPointerDown = false;
  94121. this._lastInteractionTime = -Infinity;
  94122. // Framing control
  94123. this._animatables = new Array();
  94124. this._betaIsAnimating = false;
  94125. }
  94126. Object.defineProperty(FramingBehavior.prototype, "name", {
  94127. get: function () {
  94128. return "Framing";
  94129. },
  94130. enumerable: true,
  94131. configurable: true
  94132. });
  94133. Object.defineProperty(FramingBehavior.prototype, "mode", {
  94134. /**
  94135. * Gets current mode used by the behavior.
  94136. */
  94137. get: function () {
  94138. return this._mode;
  94139. },
  94140. /**
  94141. * Sets the current mode used by the behavior
  94142. */
  94143. set: function (mode) {
  94144. this._mode = mode;
  94145. },
  94146. enumerable: true,
  94147. configurable: true
  94148. });
  94149. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  94150. /**
  94151. * Gets the scale applied to the radius
  94152. */
  94153. get: function () {
  94154. return this._radiusScale;
  94155. },
  94156. /**
  94157. * Sets the scale applied to the radius (1 by default)
  94158. */
  94159. set: function (radius) {
  94160. this._radiusScale = radius;
  94161. },
  94162. enumerable: true,
  94163. configurable: true
  94164. });
  94165. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  94166. /**
  94167. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  94168. */
  94169. get: function () {
  94170. return this._positionScale;
  94171. },
  94172. /**
  94173. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  94174. */
  94175. set: function (scale) {
  94176. this._positionScale = scale;
  94177. },
  94178. enumerable: true,
  94179. configurable: true
  94180. });
  94181. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  94182. /**
  94183. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  94184. * behaviour is triggered, in radians.
  94185. */
  94186. get: function () {
  94187. return this._defaultElevation;
  94188. },
  94189. /**
  94190. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  94191. * behaviour is triggered, in radians.
  94192. */
  94193. set: function (elevation) {
  94194. this._defaultElevation = elevation;
  94195. },
  94196. enumerable: true,
  94197. configurable: true
  94198. });
  94199. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  94200. /**
  94201. * Gets the time (in milliseconds) taken to return to the default beta position.
  94202. * Negative value indicates camera should not return to default.
  94203. */
  94204. get: function () {
  94205. return this._elevationReturnTime;
  94206. },
  94207. /**
  94208. * Sets the time (in milliseconds) taken to return to the default beta position.
  94209. * Negative value indicates camera should not return to default.
  94210. */
  94211. set: function (speed) {
  94212. this._elevationReturnTime = speed;
  94213. },
  94214. enumerable: true,
  94215. configurable: true
  94216. });
  94217. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  94218. /**
  94219. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  94220. */
  94221. get: function () {
  94222. return this._elevationReturnWaitTime;
  94223. },
  94224. /**
  94225. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  94226. */
  94227. set: function (time) {
  94228. this._elevationReturnWaitTime = time;
  94229. },
  94230. enumerable: true,
  94231. configurable: true
  94232. });
  94233. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  94234. /**
  94235. * Gets the flag that indicates if user zooming should stop animation.
  94236. */
  94237. get: function () {
  94238. return this._zoomStopsAnimation;
  94239. },
  94240. /**
  94241. * Sets the flag that indicates if user zooming should stop animation.
  94242. */
  94243. set: function (flag) {
  94244. this._zoomStopsAnimation = flag;
  94245. },
  94246. enumerable: true,
  94247. configurable: true
  94248. });
  94249. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  94250. /**
  94251. * Gets the transition time when framing the mesh, in milliseconds
  94252. */
  94253. get: function () {
  94254. return this._framingTime;
  94255. },
  94256. /**
  94257. * Sets the transition time when framing the mesh, in milliseconds
  94258. */
  94259. set: function (time) {
  94260. this._framingTime = time;
  94261. },
  94262. enumerable: true,
  94263. configurable: true
  94264. });
  94265. FramingBehavior.prototype.init = function () {
  94266. // Do notihng
  94267. };
  94268. FramingBehavior.prototype.attach = function (camera) {
  94269. var _this = this;
  94270. this._attachedCamera = camera;
  94271. var scene = this._attachedCamera.getScene();
  94272. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  94273. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  94274. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  94275. _this._isPointerDown = true;
  94276. return;
  94277. }
  94278. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  94279. _this._isPointerDown = false;
  94280. }
  94281. });
  94282. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  94283. if (mesh) {
  94284. _this.zoomOnMesh(mesh);
  94285. }
  94286. });
  94287. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  94288. // Stop the animation if there is user interaction and the animation should stop for this interaction
  94289. _this._applyUserInteraction();
  94290. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  94291. // back to the default position after a given timeout
  94292. _this._maintainCameraAboveGround();
  94293. });
  94294. };
  94295. FramingBehavior.prototype.detach = function () {
  94296. if (!this._attachedCamera) {
  94297. return;
  94298. }
  94299. var scene = this._attachedCamera.getScene();
  94300. if (this._onPrePointerObservableObserver) {
  94301. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  94302. }
  94303. if (this._onAfterCheckInputsObserver) {
  94304. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  94305. }
  94306. if (this._onMeshTargetChangedObserver) {
  94307. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  94308. }
  94309. this._attachedCamera = null;
  94310. };
  94311. /**
  94312. * Targets the given mesh and updates zoom level accordingly.
  94313. * @param mesh The mesh to target.
  94314. * @param radius Optional. If a cached radius position already exists, overrides default.
  94315. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  94316. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  94317. * @param onAnimationEnd Callback triggered at the end of the framing animation
  94318. */
  94319. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  94320. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  94321. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  94322. mesh.computeWorldMatrix(true);
  94323. var boundingBox = mesh.getBoundingInfo().boundingBox;
  94324. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  94325. };
  94326. /**
  94327. * Targets the given mesh with its children and updates zoom level accordingly.
  94328. * @param mesh The mesh to target.
  94329. * @param radius Optional. If a cached radius position already exists, overrides default.
  94330. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  94331. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  94332. * @param onAnimationEnd Callback triggered at the end of the framing animation
  94333. */
  94334. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  94335. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  94336. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  94337. mesh.computeWorldMatrix(true);
  94338. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  94339. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  94340. };
  94341. /**
  94342. * Targets the given meshes with their children and updates zoom level accordingly.
  94343. * @param meshes The mesh to target.
  94344. * @param radius Optional. If a cached radius position already exists, overrides default.
  94345. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  94346. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  94347. * @param onAnimationEnd Callback triggered at the end of the framing animation
  94348. */
  94349. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  94350. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  94351. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  94352. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  94353. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  94354. for (var i = 0; i < meshes.length; i++) {
  94355. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  94356. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  94357. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  94358. }
  94359. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  94360. };
  94361. /**
  94362. * Targets the given mesh and updates zoom level accordingly.
  94363. * @param mesh The mesh to target.
  94364. * @param radius Optional. If a cached radius position already exists, overrides default.
  94365. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  94366. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  94367. * @param onAnimationEnd Callback triggered at the end of the framing animation
  94368. */
  94369. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  94370. var _this = this;
  94371. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  94372. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  94373. var zoomTarget;
  94374. if (!this._attachedCamera) {
  94375. return;
  94376. }
  94377. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  94378. var bottom = minimumWorld.y;
  94379. var top = maximumWorld.y;
  94380. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  94381. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  94382. if (focusOnOriginXZ) {
  94383. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  94384. }
  94385. else {
  94386. var centerWorld = minimumWorld.add(radiusWorld);
  94387. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  94388. }
  94389. if (!this._vectorTransition) {
  94390. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  94391. }
  94392. this._betaIsAnimating = true;
  94393. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  94394. if (animatable) {
  94395. this._animatables.push(animatable);
  94396. }
  94397. // sets the radius and lower radius bounds
  94398. // Small delta ensures camera is not always at lower zoom limit.
  94399. var radius = 0;
  94400. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  94401. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  94402. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  94403. radius = position;
  94404. }
  94405. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  94406. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  94407. if (this._attachedCamera.lowerRadiusLimit === null) {
  94408. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  94409. }
  94410. }
  94411. // Set sensibilities
  94412. var extend = maximumWorld.subtract(minimumWorld).length();
  94413. this._attachedCamera.panningSensibility = 5000 / extend;
  94414. this._attachedCamera.wheelPrecision = 100 / radius;
  94415. // transition to new radius
  94416. if (!this._radiusTransition) {
  94417. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  94418. }
  94419. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  94420. _this.stopAllAnimations();
  94421. if (onAnimationEnd) {
  94422. onAnimationEnd();
  94423. }
  94424. if (_this._attachedCamera) {
  94425. _this._attachedCamera.storeState();
  94426. }
  94427. });
  94428. if (animatable) {
  94429. this._animatables.push(animatable);
  94430. }
  94431. };
  94432. /**
  94433. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  94434. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  94435. * frustum width.
  94436. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  94437. * to fully enclose the mesh in the viewing frustum.
  94438. */
  94439. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  94440. var size = maximumWorld.subtract(minimumWorld);
  94441. var boxVectorGlobalDiagonal = size.length();
  94442. var frustumSlope = this._getFrustumSlope();
  94443. // Formula for setting distance
  94444. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  94445. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  94446. // Horizon distance
  94447. var radius = radiusWithoutFraming * this._radiusScale;
  94448. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  94449. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  94450. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  94451. var camera = this._attachedCamera;
  94452. if (!camera) {
  94453. return 0;
  94454. }
  94455. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  94456. // Don't exceed the requested limit
  94457. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  94458. }
  94459. // Don't exceed the upper radius limit
  94460. if (camera.upperRadiusLimit) {
  94461. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  94462. }
  94463. return distance;
  94464. };
  94465. /**
  94466. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  94467. * is automatically returned to its default position (expected to be above ground plane).
  94468. */
  94469. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  94470. var _this = this;
  94471. if (this._elevationReturnTime < 0) {
  94472. return;
  94473. }
  94474. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  94475. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  94476. var limitBeta = Math.PI * 0.5;
  94477. // Bring the camera back up if below the ground plane
  94478. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  94479. this._betaIsAnimating = true;
  94480. //Transition to new position
  94481. this.stopAllAnimations();
  94482. if (!this._betaTransition) {
  94483. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  94484. }
  94485. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  94486. _this._clearAnimationLocks();
  94487. _this.stopAllAnimations();
  94488. });
  94489. if (animatabe) {
  94490. this._animatables.push(animatabe);
  94491. }
  94492. }
  94493. };
  94494. /**
  94495. * Returns the frustum slope based on the canvas ratio and camera FOV
  94496. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  94497. */
  94498. FramingBehavior.prototype._getFrustumSlope = function () {
  94499. // Calculate the viewport ratio
  94500. // Aspect Ratio is Height/Width.
  94501. var camera = this._attachedCamera;
  94502. if (!camera) {
  94503. return BABYLON.Vector2.Zero();
  94504. }
  94505. var engine = camera.getScene().getEngine();
  94506. var aspectRatio = engine.getAspectRatio(camera);
  94507. // Camera FOV is the vertical field of view (top-bottom) in radians.
  94508. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  94509. var frustumSlopeY = Math.tan(camera.fov / 2);
  94510. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  94511. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  94512. // along the forward vector.
  94513. var frustumSlopeX = frustumSlopeY * aspectRatio;
  94514. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  94515. };
  94516. /**
  94517. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  94518. */
  94519. FramingBehavior.prototype._clearAnimationLocks = function () {
  94520. this._betaIsAnimating = false;
  94521. };
  94522. /**
  94523. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  94524. */
  94525. FramingBehavior.prototype._applyUserInteraction = function () {
  94526. if (this.isUserIsMoving) {
  94527. this._lastInteractionTime = BABYLON.Tools.Now;
  94528. this.stopAllAnimations();
  94529. this._clearAnimationLocks();
  94530. }
  94531. };
  94532. /**
  94533. * Stops and removes all animations that have been applied to the camera
  94534. */
  94535. FramingBehavior.prototype.stopAllAnimations = function () {
  94536. if (this._attachedCamera) {
  94537. this._attachedCamera.animations = [];
  94538. }
  94539. while (this._animatables.length) {
  94540. if (this._animatables[0]) {
  94541. this._animatables[0].onAnimationEnd = null;
  94542. this._animatables[0].stop();
  94543. }
  94544. this._animatables.shift();
  94545. }
  94546. };
  94547. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  94548. /**
  94549. * Gets a value indicating if the user is moving the camera
  94550. */
  94551. get: function () {
  94552. if (!this._attachedCamera) {
  94553. return false;
  94554. }
  94555. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  94556. this._attachedCamera.inertialBetaOffset !== 0 ||
  94557. this._attachedCamera.inertialRadiusOffset !== 0 ||
  94558. this._attachedCamera.inertialPanningX !== 0 ||
  94559. this._attachedCamera.inertialPanningY !== 0 ||
  94560. this._isPointerDown;
  94561. },
  94562. enumerable: true,
  94563. configurable: true
  94564. });
  94565. /**
  94566. * The easing function used by animations
  94567. */
  94568. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  94569. /**
  94570. * The easing mode used by animations
  94571. */
  94572. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  94573. // Statics
  94574. /**
  94575. * The camera can move all the way towards the mesh.
  94576. */
  94577. FramingBehavior.IgnoreBoundsSizeMode = 0;
  94578. /**
  94579. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  94580. */
  94581. FramingBehavior.FitFrustumSidesMode = 1;
  94582. return FramingBehavior;
  94583. }());
  94584. BABYLON.FramingBehavior = FramingBehavior;
  94585. })(BABYLON || (BABYLON = {}));
  94586. //# sourceMappingURL=babylon.framingBehavior.js.map
  94587. var BABYLON;
  94588. (function (BABYLON) {
  94589. /**
  94590. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  94591. */
  94592. var BouncingBehavior = /** @class */ (function () {
  94593. function BouncingBehavior() {
  94594. /**
  94595. * The duration of the animation, in milliseconds
  94596. */
  94597. this.transitionDuration = 450;
  94598. /**
  94599. * Length of the distance animated by the transition when lower radius is reached
  94600. */
  94601. this.lowerRadiusTransitionRange = 2;
  94602. /**
  94603. * Length of the distance animated by the transition when upper radius is reached
  94604. */
  94605. this.upperRadiusTransitionRange = -2;
  94606. this._autoTransitionRange = false;
  94607. // Animations
  94608. this._radiusIsAnimating = false;
  94609. this._radiusBounceTransition = null;
  94610. this._animatables = new Array();
  94611. }
  94612. Object.defineProperty(BouncingBehavior.prototype, "name", {
  94613. get: function () {
  94614. return "Bouncing";
  94615. },
  94616. enumerable: true,
  94617. configurable: true
  94618. });
  94619. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  94620. /**
  94621. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  94622. */
  94623. get: function () {
  94624. return this._autoTransitionRange;
  94625. },
  94626. /**
  94627. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  94628. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  94629. */
  94630. set: function (value) {
  94631. var _this = this;
  94632. if (this._autoTransitionRange === value) {
  94633. return;
  94634. }
  94635. this._autoTransitionRange = value;
  94636. var camera = this._attachedCamera;
  94637. if (!camera) {
  94638. return;
  94639. }
  94640. if (value) {
  94641. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  94642. if (!mesh) {
  94643. return;
  94644. }
  94645. mesh.computeWorldMatrix(true);
  94646. var diagonal = mesh.getBoundingInfo().diagonalLength;
  94647. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  94648. _this.upperRadiusTransitionRange = diagonal * 0.05;
  94649. });
  94650. }
  94651. else if (this._onMeshTargetChangedObserver) {
  94652. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  94653. }
  94654. },
  94655. enumerable: true,
  94656. configurable: true
  94657. });
  94658. BouncingBehavior.prototype.init = function () {
  94659. // Do notihng
  94660. };
  94661. BouncingBehavior.prototype.attach = function (camera) {
  94662. var _this = this;
  94663. this._attachedCamera = camera;
  94664. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  94665. if (!_this._attachedCamera) {
  94666. return;
  94667. }
  94668. // Add the bounce animation to the lower radius limit
  94669. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  94670. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  94671. }
  94672. // Add the bounce animation to the upper radius limit
  94673. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  94674. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  94675. }
  94676. });
  94677. };
  94678. BouncingBehavior.prototype.detach = function () {
  94679. if (!this._attachedCamera) {
  94680. return;
  94681. }
  94682. if (this._onAfterCheckInputsObserver) {
  94683. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  94684. }
  94685. if (this._onMeshTargetChangedObserver) {
  94686. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  94687. }
  94688. this._attachedCamera = null;
  94689. };
  94690. /**
  94691. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  94692. * @param radiusLimit The limit to check against.
  94693. * @return Bool to indicate if at limit.
  94694. */
  94695. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  94696. if (!this._attachedCamera) {
  94697. return false;
  94698. }
  94699. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  94700. return true;
  94701. }
  94702. return false;
  94703. };
  94704. /**
  94705. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  94706. * @param radiusDelta The delta by which to animate to. Can be negative.
  94707. */
  94708. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  94709. var _this = this;
  94710. if (!this._attachedCamera) {
  94711. return;
  94712. }
  94713. if (!this._radiusBounceTransition) {
  94714. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  94715. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  94716. }
  94717. // Prevent zoom until bounce has completed
  94718. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  94719. this._attachedCamera.wheelPrecision = Infinity;
  94720. this._attachedCamera.inertialRadiusOffset = 0;
  94721. // Animate to the radius limit
  94722. this.stopAllAnimations();
  94723. this._radiusIsAnimating = true;
  94724. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  94725. if (animatable) {
  94726. this._animatables.push(animatable);
  94727. }
  94728. };
  94729. /**
  94730. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  94731. */
  94732. BouncingBehavior.prototype._clearAnimationLocks = function () {
  94733. this._radiusIsAnimating = false;
  94734. if (this._attachedCamera) {
  94735. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  94736. }
  94737. };
  94738. /**
  94739. * Stops and removes all animations that have been applied to the camera
  94740. */
  94741. BouncingBehavior.prototype.stopAllAnimations = function () {
  94742. if (this._attachedCamera) {
  94743. this._attachedCamera.animations = [];
  94744. }
  94745. while (this._animatables.length) {
  94746. this._animatables[0].onAnimationEnd = null;
  94747. this._animatables[0].stop();
  94748. this._animatables.shift();
  94749. }
  94750. };
  94751. /**
  94752. * The easing function used by animations
  94753. */
  94754. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  94755. /**
  94756. * The easing mode used by animations
  94757. */
  94758. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  94759. return BouncingBehavior;
  94760. }());
  94761. BABYLON.BouncingBehavior = BouncingBehavior;
  94762. })(BABYLON || (BABYLON = {}));
  94763. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  94764. var BABYLON;
  94765. (function (BABYLON) {
  94766. var AutoRotationBehavior = /** @class */ (function () {
  94767. function AutoRotationBehavior() {
  94768. this._zoomStopsAnimation = false;
  94769. this._idleRotationSpeed = 0.05;
  94770. this._idleRotationWaitTime = 2000;
  94771. this._idleRotationSpinupTime = 2000;
  94772. this._isPointerDown = false;
  94773. this._lastFrameTime = null;
  94774. this._lastInteractionTime = -Infinity;
  94775. this._cameraRotationSpeed = 0;
  94776. this._lastFrameRadius = 0;
  94777. }
  94778. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  94779. get: function () {
  94780. return "AutoRotation";
  94781. },
  94782. enumerable: true,
  94783. configurable: true
  94784. });
  94785. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  94786. /**
  94787. * Gets the flag that indicates if user zooming should stop animation.
  94788. */
  94789. get: function () {
  94790. return this._zoomStopsAnimation;
  94791. },
  94792. /**
  94793. * Sets the flag that indicates if user zooming should stop animation.
  94794. */
  94795. set: function (flag) {
  94796. this._zoomStopsAnimation = flag;
  94797. },
  94798. enumerable: true,
  94799. configurable: true
  94800. });
  94801. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  94802. /**
  94803. * Gets the default speed at which the camera rotates around the model.
  94804. */
  94805. get: function () {
  94806. return this._idleRotationSpeed;
  94807. },
  94808. /**
  94809. * Sets the default speed at which the camera rotates around the model.
  94810. */
  94811. set: function (speed) {
  94812. this._idleRotationSpeed = speed;
  94813. },
  94814. enumerable: true,
  94815. configurable: true
  94816. });
  94817. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  94818. /**
  94819. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  94820. */
  94821. get: function () {
  94822. return this._idleRotationWaitTime;
  94823. },
  94824. /**
  94825. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  94826. */
  94827. set: function (time) {
  94828. this._idleRotationWaitTime = time;
  94829. },
  94830. enumerable: true,
  94831. configurable: true
  94832. });
  94833. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  94834. /**
  94835. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  94836. */
  94837. get: function () {
  94838. return this._idleRotationSpinupTime;
  94839. },
  94840. /**
  94841. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  94842. */
  94843. set: function (time) {
  94844. this._idleRotationSpinupTime = time;
  94845. },
  94846. enumerable: true,
  94847. configurable: true
  94848. });
  94849. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  94850. /**
  94851. * Gets a value indicating if the camera is currently rotating because of this behavior
  94852. */
  94853. get: function () {
  94854. return Math.abs(this._cameraRotationSpeed) > 0;
  94855. },
  94856. enumerable: true,
  94857. configurable: true
  94858. });
  94859. AutoRotationBehavior.prototype.init = function () {
  94860. // Do notihng
  94861. };
  94862. AutoRotationBehavior.prototype.attach = function (camera) {
  94863. var _this = this;
  94864. this._attachedCamera = camera;
  94865. var scene = this._attachedCamera.getScene();
  94866. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  94867. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  94868. _this._isPointerDown = true;
  94869. return;
  94870. }
  94871. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  94872. _this._isPointerDown = false;
  94873. }
  94874. });
  94875. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  94876. var now = BABYLON.Tools.Now;
  94877. var dt = 0;
  94878. if (_this._lastFrameTime != null) {
  94879. dt = now - _this._lastFrameTime;
  94880. }
  94881. _this._lastFrameTime = now;
  94882. // Stop the animation if there is user interaction and the animation should stop for this interaction
  94883. _this._applyUserInteraction();
  94884. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  94885. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  94886. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  94887. // Step camera rotation by rotation speed
  94888. if (_this._attachedCamera) {
  94889. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  94890. }
  94891. });
  94892. };
  94893. AutoRotationBehavior.prototype.detach = function () {
  94894. if (!this._attachedCamera) {
  94895. return;
  94896. }
  94897. var scene = this._attachedCamera.getScene();
  94898. if (this._onPrePointerObservableObserver) {
  94899. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  94900. }
  94901. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  94902. this._attachedCamera = null;
  94903. };
  94904. /**
  94905. * Returns true if user is scrolling.
  94906. * @return true if user is scrolling.
  94907. */
  94908. AutoRotationBehavior.prototype._userIsZooming = function () {
  94909. if (!this._attachedCamera) {
  94910. return false;
  94911. }
  94912. return this._attachedCamera.inertialRadiusOffset !== 0;
  94913. };
  94914. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  94915. if (!this._attachedCamera) {
  94916. return false;
  94917. }
  94918. var zoomHasHitLimit = false;
  94919. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  94920. zoomHasHitLimit = true;
  94921. }
  94922. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  94923. this._lastFrameRadius = this._attachedCamera.radius;
  94924. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  94925. };
  94926. /**
  94927. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  94928. */
  94929. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  94930. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  94931. this._lastInteractionTime = BABYLON.Tools.Now;
  94932. }
  94933. };
  94934. // Tools
  94935. AutoRotationBehavior.prototype._userIsMoving = function () {
  94936. if (!this._attachedCamera) {
  94937. return false;
  94938. }
  94939. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  94940. this._attachedCamera.inertialBetaOffset !== 0 ||
  94941. this._attachedCamera.inertialRadiusOffset !== 0 ||
  94942. this._attachedCamera.inertialPanningX !== 0 ||
  94943. this._attachedCamera.inertialPanningY !== 0 ||
  94944. this._isPointerDown;
  94945. };
  94946. return AutoRotationBehavior;
  94947. }());
  94948. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  94949. })(BABYLON || (BABYLON = {}));
  94950. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  94951. var BABYLON;
  94952. (function (BABYLON) {
  94953. var NullEngineOptions = /** @class */ (function () {
  94954. function NullEngineOptions() {
  94955. this.renderWidth = 512;
  94956. this.renderHeight = 256;
  94957. this.textureSize = 512;
  94958. this.deterministicLockstep = false;
  94959. this.lockstepMaxSteps = 4;
  94960. }
  94961. return NullEngineOptions;
  94962. }());
  94963. BABYLON.NullEngineOptions = NullEngineOptions;
  94964. /**
  94965. * The null engine class provides support for headless version of babylon.js.
  94966. * This can be used in server side scenario or for testing purposes
  94967. */
  94968. var NullEngine = /** @class */ (function (_super) {
  94969. __extends(NullEngine, _super);
  94970. function NullEngine(options) {
  94971. if (options === void 0) { options = new NullEngineOptions(); }
  94972. var _this = _super.call(this, null) || this;
  94973. if (options.deterministicLockstep === undefined) {
  94974. options.deterministicLockstep = false;
  94975. }
  94976. if (options.lockstepMaxSteps === undefined) {
  94977. options.lockstepMaxSteps = 4;
  94978. }
  94979. _this._options = options;
  94980. // Init caps
  94981. // We consider we are on a webgl1 capable device
  94982. _this._caps = new BABYLON.EngineCapabilities();
  94983. _this._caps.maxTexturesImageUnits = 16;
  94984. _this._caps.maxVertexTextureImageUnits = 16;
  94985. _this._caps.maxTextureSize = 512;
  94986. _this._caps.maxCubemapTextureSize = 512;
  94987. _this._caps.maxRenderTextureSize = 512;
  94988. _this._caps.maxVertexAttribs = 16;
  94989. _this._caps.maxVaryingVectors = 16;
  94990. _this._caps.maxFragmentUniformVectors = 16;
  94991. _this._caps.maxVertexUniformVectors = 16;
  94992. // Extensions
  94993. _this._caps.standardDerivatives = false;
  94994. _this._caps.astc = null;
  94995. _this._caps.s3tc = null;
  94996. _this._caps.pvrtc = null;
  94997. _this._caps.etc1 = null;
  94998. _this._caps.etc2 = null;
  94999. _this._caps.textureAnisotropicFilterExtension = null;
  95000. _this._caps.maxAnisotropy = 0;
  95001. _this._caps.uintIndices = false;
  95002. _this._caps.fragmentDepthSupported = false;
  95003. _this._caps.highPrecisionShaderSupported = true;
  95004. _this._caps.colorBufferFloat = false;
  95005. _this._caps.textureFloat = false;
  95006. _this._caps.textureFloatLinearFiltering = false;
  95007. _this._caps.textureFloatRender = false;
  95008. _this._caps.textureHalfFloat = false;
  95009. _this._caps.textureHalfFloatLinearFiltering = false;
  95010. _this._caps.textureHalfFloatRender = false;
  95011. _this._caps.textureLOD = false;
  95012. _this._caps.drawBuffersExtension = false;
  95013. _this._caps.depthTextureExtension = false;
  95014. _this._caps.vertexArrayObject = false;
  95015. _this._caps.instancedArrays = false;
  95016. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  95017. // Wrappers
  95018. if (typeof URL === "undefined") {
  95019. URL = {
  95020. createObjectURL: function () { },
  95021. revokeObjectURL: function () { }
  95022. };
  95023. }
  95024. if (typeof Blob === "undefined") {
  95025. Blob = function () { };
  95026. }
  95027. return _this;
  95028. }
  95029. NullEngine.prototype.isDeterministicLockStep = function () {
  95030. return this._options.deterministicLockstep;
  95031. };
  95032. NullEngine.prototype.getLockstepMaxSteps = function () {
  95033. return this._options.lockstepMaxSteps;
  95034. };
  95035. NullEngine.prototype.getHardwareScalingLevel = function () {
  95036. return 1.0;
  95037. };
  95038. NullEngine.prototype.createVertexBuffer = function (vertices) {
  95039. return {
  95040. capacity: 0,
  95041. references: 1,
  95042. is32Bits: false
  95043. };
  95044. };
  95045. NullEngine.prototype.createIndexBuffer = function (indices) {
  95046. return {
  95047. capacity: 0,
  95048. references: 1,
  95049. is32Bits: false
  95050. };
  95051. };
  95052. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  95053. if (stencil === void 0) { stencil = false; }
  95054. };
  95055. NullEngine.prototype.getRenderWidth = function (useScreen) {
  95056. if (useScreen === void 0) { useScreen = false; }
  95057. if (!useScreen && this._currentRenderTarget) {
  95058. return this._currentRenderTarget.width;
  95059. }
  95060. return this._options.renderWidth;
  95061. };
  95062. NullEngine.prototype.getRenderHeight = function (useScreen) {
  95063. if (useScreen === void 0) { useScreen = false; }
  95064. if (!useScreen && this._currentRenderTarget) {
  95065. return this._currentRenderTarget.height;
  95066. }
  95067. return this._options.renderHeight;
  95068. };
  95069. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  95070. this._cachedViewport = viewport;
  95071. };
  95072. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  95073. return {
  95074. transformFeedback: null,
  95075. __SPECTOR_rebuildProgram: null
  95076. };
  95077. };
  95078. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  95079. return [];
  95080. };
  95081. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  95082. return [];
  95083. };
  95084. NullEngine.prototype.bindSamplers = function (effect) {
  95085. this._currentEffect = null;
  95086. };
  95087. NullEngine.prototype.enableEffect = function (effect) {
  95088. this._currentEffect = effect;
  95089. if (effect.onBind) {
  95090. effect.onBind(effect);
  95091. }
  95092. effect.onBindObservable.notifyObservers(effect);
  95093. };
  95094. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  95095. if (zOffset === void 0) { zOffset = 0; }
  95096. if (reverseSide === void 0) { reverseSide = false; }
  95097. };
  95098. NullEngine.prototype.setIntArray = function (uniform, array) {
  95099. };
  95100. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  95101. };
  95102. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  95103. };
  95104. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  95105. };
  95106. NullEngine.prototype.setFloatArray = function (uniform, array) {
  95107. };
  95108. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  95109. };
  95110. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  95111. };
  95112. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  95113. };
  95114. NullEngine.prototype.setArray = function (uniform, array) {
  95115. };
  95116. NullEngine.prototype.setArray2 = function (uniform, array) {
  95117. };
  95118. NullEngine.prototype.setArray3 = function (uniform, array) {
  95119. };
  95120. NullEngine.prototype.setArray4 = function (uniform, array) {
  95121. };
  95122. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  95123. };
  95124. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  95125. };
  95126. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  95127. };
  95128. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  95129. };
  95130. NullEngine.prototype.setFloat = function (uniform, value) {
  95131. };
  95132. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  95133. };
  95134. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  95135. };
  95136. NullEngine.prototype.setBool = function (uniform, bool) {
  95137. };
  95138. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  95139. };
  95140. NullEngine.prototype.setColor3 = function (uniform, color3) {
  95141. };
  95142. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  95143. };
  95144. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  95145. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  95146. if (this._alphaMode === mode) {
  95147. return;
  95148. }
  95149. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  95150. if (!noDepthWriteChange) {
  95151. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  95152. }
  95153. this._alphaMode = mode;
  95154. };
  95155. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  95156. };
  95157. NullEngine.prototype.wipeCaches = function (bruteForce) {
  95158. if (this.preventCacheWipeBetweenFrames) {
  95159. return;
  95160. }
  95161. this.resetTextureCache();
  95162. this._currentEffect = null;
  95163. if (bruteForce) {
  95164. this._currentProgram = null;
  95165. this._stencilState.reset();
  95166. this._depthCullingState.reset();
  95167. this._alphaState.reset();
  95168. }
  95169. this._cachedVertexBuffers = null;
  95170. this._cachedIndexBuffer = null;
  95171. this._cachedEffectForVertexBuffers = null;
  95172. };
  95173. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  95174. };
  95175. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  95176. };
  95177. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  95178. };
  95179. NullEngine.prototype._createTexture = function () {
  95180. return {};
  95181. };
  95182. NullEngine.prototype._releaseTexture = function (texture) {
  95183. };
  95184. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  95185. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  95186. if (onLoad === void 0) { onLoad = null; }
  95187. if (onError === void 0) { onError = null; }
  95188. if (buffer === void 0) { buffer = null; }
  95189. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  95190. var url = String(urlArg);
  95191. texture.url = url;
  95192. texture.generateMipMaps = !noMipmap;
  95193. texture.samplingMode = samplingMode;
  95194. texture.invertY = invertY;
  95195. texture.baseWidth = this._options.textureSize;
  95196. texture.baseHeight = this._options.textureSize;
  95197. texture.width = this._options.textureSize;
  95198. texture.height = this._options.textureSize;
  95199. if (format) {
  95200. texture.format = format;
  95201. }
  95202. texture.isReady = true;
  95203. if (onLoad) {
  95204. onLoad();
  95205. }
  95206. return texture;
  95207. };
  95208. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  95209. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  95210. if (options !== undefined && typeof options === "object") {
  95211. fullOptions.generateMipMaps = options.generateMipMaps;
  95212. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  95213. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  95214. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  95215. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  95216. }
  95217. else {
  95218. fullOptions.generateMipMaps = options;
  95219. fullOptions.generateDepthBuffer = true;
  95220. fullOptions.generateStencilBuffer = false;
  95221. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  95222. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  95223. }
  95224. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  95225. var width = size.width || size;
  95226. var height = size.height || size;
  95227. texture._depthStencilBuffer = {};
  95228. texture._framebuffer = {};
  95229. texture.baseWidth = width;
  95230. texture.baseHeight = height;
  95231. texture.width = width;
  95232. texture.height = height;
  95233. texture.isReady = true;
  95234. texture.samples = 1;
  95235. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  95236. texture.samplingMode = fullOptions.samplingMode;
  95237. texture.type = fullOptions.type;
  95238. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  95239. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  95240. return texture;
  95241. };
  95242. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  95243. texture.samplingMode = samplingMode;
  95244. };
  95245. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  95246. if (this._currentRenderTarget) {
  95247. this.unBindFramebuffer(this._currentRenderTarget);
  95248. }
  95249. this._currentRenderTarget = texture;
  95250. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  95251. if (this._cachedViewport && !forceFullscreenViewport) {
  95252. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  95253. }
  95254. };
  95255. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  95256. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  95257. this._currentRenderTarget = null;
  95258. if (onBeforeUnbind) {
  95259. if (texture._MSAAFramebuffer) {
  95260. this._currentFramebuffer = texture._framebuffer;
  95261. }
  95262. onBeforeUnbind();
  95263. }
  95264. this._currentFramebuffer = null;
  95265. };
  95266. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  95267. var vbo = {
  95268. capacity: 1,
  95269. references: 1,
  95270. is32Bits: false
  95271. };
  95272. return vbo;
  95273. };
  95274. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  95275. if (offset === void 0) { offset = 0; }
  95276. };
  95277. /**
  95278. * Updates a dynamic vertex buffer.
  95279. * @param vertexBuffer the vertex buffer to update
  95280. * @param data the data used to update the vertex buffer
  95281. * @param byteOffset the byte offset of the data (optional)
  95282. * @param byteLength the byte length of the data (optional)
  95283. */
  95284. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  95285. };
  95286. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  95287. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  95288. this._boundTexturesCache[this._activeChannel] = texture;
  95289. }
  95290. };
  95291. NullEngine.prototype._bindTexture = function (channel, texture) {
  95292. if (channel < 0) {
  95293. return;
  95294. }
  95295. this._bindTextureDirectly(0, texture);
  95296. };
  95297. NullEngine.prototype._releaseBuffer = function (buffer) {
  95298. buffer.references--;
  95299. if (buffer.references === 0) {
  95300. return true;
  95301. }
  95302. return false;
  95303. };
  95304. NullEngine.prototype.releaseEffects = function () {
  95305. };
  95306. return NullEngine;
  95307. }(BABYLON.Engine));
  95308. BABYLON.NullEngine = NullEngine;
  95309. })(BABYLON || (BABYLON = {}));
  95310. //# sourceMappingURL=babylon.nullEngine.js.map
  95311. var BABYLON;
  95312. (function (BABYLON) {
  95313. /**
  95314. * This class can be used to get instrumentation data from a Babylon engine
  95315. */
  95316. var EngineInstrumentation = /** @class */ (function () {
  95317. function EngineInstrumentation(engine) {
  95318. this.engine = engine;
  95319. this._captureGPUFrameTime = false;
  95320. this._gpuFrameTime = new BABYLON.PerfCounter();
  95321. this._captureShaderCompilationTime = false;
  95322. this._shaderCompilationTime = new BABYLON.PerfCounter();
  95323. // Observers
  95324. this._onBeginFrameObserver = null;
  95325. this._onEndFrameObserver = null;
  95326. this._onBeforeShaderCompilationObserver = null;
  95327. this._onAfterShaderCompilationObserver = null;
  95328. }
  95329. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  95330. // Properties
  95331. /**
  95332. * Gets the perf counter used for GPU frame time
  95333. */
  95334. get: function () {
  95335. return this._gpuFrameTime;
  95336. },
  95337. enumerable: true,
  95338. configurable: true
  95339. });
  95340. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  95341. /**
  95342. * Gets the GPU frame time capture status
  95343. */
  95344. get: function () {
  95345. return this._captureGPUFrameTime;
  95346. },
  95347. /**
  95348. * Enable or disable the GPU frame time capture
  95349. */
  95350. set: function (value) {
  95351. var _this = this;
  95352. if (value === this._captureGPUFrameTime) {
  95353. return;
  95354. }
  95355. this._captureGPUFrameTime = value;
  95356. if (value) {
  95357. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  95358. if (!_this._gpuFrameTimeToken) {
  95359. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  95360. }
  95361. });
  95362. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  95363. if (!_this._gpuFrameTimeToken) {
  95364. return;
  95365. }
  95366. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  95367. if (time > -1) {
  95368. _this._gpuFrameTimeToken = null;
  95369. _this._gpuFrameTime.fetchNewFrame();
  95370. _this._gpuFrameTime.addCount(time, true);
  95371. }
  95372. });
  95373. }
  95374. else {
  95375. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  95376. this._onBeginFrameObserver = null;
  95377. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  95378. this._onEndFrameObserver = null;
  95379. }
  95380. },
  95381. enumerable: true,
  95382. configurable: true
  95383. });
  95384. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  95385. /**
  95386. * Gets the perf counter used for shader compilation time
  95387. */
  95388. get: function () {
  95389. return this._shaderCompilationTime;
  95390. },
  95391. enumerable: true,
  95392. configurable: true
  95393. });
  95394. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  95395. /**
  95396. * Gets the shader compilation time capture status
  95397. */
  95398. get: function () {
  95399. return this._captureShaderCompilationTime;
  95400. },
  95401. /**
  95402. * Enable or disable the shader compilation time capture
  95403. */
  95404. set: function (value) {
  95405. var _this = this;
  95406. if (value === this._captureShaderCompilationTime) {
  95407. return;
  95408. }
  95409. this._captureShaderCompilationTime = value;
  95410. if (value) {
  95411. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  95412. _this._shaderCompilationTime.fetchNewFrame();
  95413. _this._shaderCompilationTime.beginMonitoring();
  95414. });
  95415. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  95416. _this._shaderCompilationTime.endMonitoring();
  95417. });
  95418. }
  95419. else {
  95420. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  95421. this._onBeforeShaderCompilationObserver = null;
  95422. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  95423. this._onAfterShaderCompilationObserver = null;
  95424. }
  95425. },
  95426. enumerable: true,
  95427. configurable: true
  95428. });
  95429. EngineInstrumentation.prototype.dispose = function () {
  95430. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  95431. this._onBeginFrameObserver = null;
  95432. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  95433. this._onEndFrameObserver = null;
  95434. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  95435. this._onBeforeShaderCompilationObserver = null;
  95436. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  95437. this._onAfterShaderCompilationObserver = null;
  95438. this.engine = null;
  95439. };
  95440. return EngineInstrumentation;
  95441. }());
  95442. BABYLON.EngineInstrumentation = EngineInstrumentation;
  95443. })(BABYLON || (BABYLON = {}));
  95444. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  95445. var BABYLON;
  95446. (function (BABYLON) {
  95447. /**
  95448. * This class can be used to get instrumentation data from a Babylon engine
  95449. */
  95450. var SceneInstrumentation = /** @class */ (function () {
  95451. function SceneInstrumentation(scene) {
  95452. var _this = this;
  95453. this.scene = scene;
  95454. this._captureActiveMeshesEvaluationTime = false;
  95455. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  95456. this._captureRenderTargetsRenderTime = false;
  95457. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  95458. this._captureFrameTime = false;
  95459. this._frameTime = new BABYLON.PerfCounter();
  95460. this._captureRenderTime = false;
  95461. this._renderTime = new BABYLON.PerfCounter();
  95462. this._captureInterFrameTime = false;
  95463. this._interFrameTime = new BABYLON.PerfCounter();
  95464. this._captureParticlesRenderTime = false;
  95465. this._particlesRenderTime = new BABYLON.PerfCounter();
  95466. this._captureSpritesRenderTime = false;
  95467. this._spritesRenderTime = new BABYLON.PerfCounter();
  95468. this._capturePhysicsTime = false;
  95469. this._physicsTime = new BABYLON.PerfCounter();
  95470. this._captureAnimationsTime = false;
  95471. this._animationsTime = new BABYLON.PerfCounter();
  95472. // Observers
  95473. this._onBeforeActiveMeshesEvaluationObserver = null;
  95474. this._onAfterActiveMeshesEvaluationObserver = null;
  95475. this._onBeforeRenderTargetsRenderObserver = null;
  95476. this._onAfterRenderTargetsRenderObserver = null;
  95477. this._onAfterRenderObserver = null;
  95478. this._onBeforeDrawPhaseObserver = null;
  95479. this._onAfterDrawPhaseObserver = null;
  95480. this._onBeforeAnimationsObserver = null;
  95481. this._onBeforeParticlesRenderingObserver = null;
  95482. this._onAfterParticlesRenderingObserver = null;
  95483. this._onBeforeSpritesRenderingObserver = null;
  95484. this._onAfterSpritesRenderingObserver = null;
  95485. this._onBeforePhysicsObserver = null;
  95486. this._onAfterPhysicsObserver = null;
  95487. this._onAfterAnimationsObserver = null;
  95488. // Before render
  95489. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  95490. if (_this._captureActiveMeshesEvaluationTime) {
  95491. _this._activeMeshesEvaluationTime.fetchNewFrame();
  95492. }
  95493. if (_this._captureRenderTargetsRenderTime) {
  95494. _this._renderTargetsRenderTime.fetchNewFrame();
  95495. }
  95496. if (_this._captureFrameTime) {
  95497. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  95498. _this._frameTime.beginMonitoring();
  95499. }
  95500. if (_this._captureInterFrameTime) {
  95501. _this._interFrameTime.endMonitoring();
  95502. }
  95503. if (_this._captureParticlesRenderTime) {
  95504. _this._particlesRenderTime.fetchNewFrame();
  95505. }
  95506. if (_this._captureSpritesRenderTime) {
  95507. _this._spritesRenderTime.fetchNewFrame();
  95508. }
  95509. if (_this._captureAnimationsTime) {
  95510. _this._animationsTime.beginMonitoring();
  95511. }
  95512. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  95513. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  95514. });
  95515. // After render
  95516. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  95517. if (_this._captureFrameTime) {
  95518. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  95519. _this._frameTime.endMonitoring();
  95520. }
  95521. if (_this._captureRenderTime) {
  95522. _this._renderTime.endMonitoring(false);
  95523. }
  95524. if (_this._captureInterFrameTime) {
  95525. _this._interFrameTime.beginMonitoring();
  95526. }
  95527. });
  95528. }
  95529. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  95530. // Properties
  95531. /**
  95532. * Gets the perf counter used for active meshes evaluation time
  95533. */
  95534. get: function () {
  95535. return this._activeMeshesEvaluationTime;
  95536. },
  95537. enumerable: true,
  95538. configurable: true
  95539. });
  95540. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  95541. /**
  95542. * Gets the active meshes evaluation time capture status
  95543. */
  95544. get: function () {
  95545. return this._captureActiveMeshesEvaluationTime;
  95546. },
  95547. /**
  95548. * Enable or disable the active meshes evaluation time capture
  95549. */
  95550. set: function (value) {
  95551. var _this = this;
  95552. if (value === this._captureActiveMeshesEvaluationTime) {
  95553. return;
  95554. }
  95555. this._captureActiveMeshesEvaluationTime = value;
  95556. if (value) {
  95557. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  95558. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  95559. _this._activeMeshesEvaluationTime.beginMonitoring();
  95560. });
  95561. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  95562. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  95563. _this._activeMeshesEvaluationTime.endMonitoring();
  95564. });
  95565. }
  95566. else {
  95567. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  95568. this._onBeforeActiveMeshesEvaluationObserver = null;
  95569. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  95570. this._onAfterActiveMeshesEvaluationObserver = null;
  95571. }
  95572. },
  95573. enumerable: true,
  95574. configurable: true
  95575. });
  95576. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  95577. /**
  95578. * Gets the perf counter used for render targets render time
  95579. */
  95580. get: function () {
  95581. return this._renderTargetsRenderTime;
  95582. },
  95583. enumerable: true,
  95584. configurable: true
  95585. });
  95586. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  95587. /**
  95588. * Gets the render targets render time capture status
  95589. */
  95590. get: function () {
  95591. return this._captureRenderTargetsRenderTime;
  95592. },
  95593. /**
  95594. * Enable or disable the render targets render time capture
  95595. */
  95596. set: function (value) {
  95597. var _this = this;
  95598. if (value === this._captureRenderTargetsRenderTime) {
  95599. return;
  95600. }
  95601. this._captureRenderTargetsRenderTime = value;
  95602. if (value) {
  95603. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  95604. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  95605. _this._renderTargetsRenderTime.beginMonitoring();
  95606. });
  95607. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  95608. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  95609. _this._renderTargetsRenderTime.endMonitoring(false);
  95610. });
  95611. }
  95612. else {
  95613. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  95614. this._onBeforeRenderTargetsRenderObserver = null;
  95615. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  95616. this._onAfterRenderTargetsRenderObserver = null;
  95617. }
  95618. },
  95619. enumerable: true,
  95620. configurable: true
  95621. });
  95622. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  95623. /**
  95624. * Gets the perf counter used for particles render time
  95625. */
  95626. get: function () {
  95627. return this._particlesRenderTime;
  95628. },
  95629. enumerable: true,
  95630. configurable: true
  95631. });
  95632. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  95633. /**
  95634. * Gets the particles render time capture status
  95635. */
  95636. get: function () {
  95637. return this._captureParticlesRenderTime;
  95638. },
  95639. /**
  95640. * Enable or disable the particles render time capture
  95641. */
  95642. set: function (value) {
  95643. var _this = this;
  95644. if (value === this._captureParticlesRenderTime) {
  95645. return;
  95646. }
  95647. this._captureParticlesRenderTime = value;
  95648. if (value) {
  95649. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  95650. BABYLON.Tools.StartPerformanceCounter("Particles");
  95651. _this._particlesRenderTime.beginMonitoring();
  95652. });
  95653. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  95654. BABYLON.Tools.EndPerformanceCounter("Particles");
  95655. _this._particlesRenderTime.endMonitoring(false);
  95656. });
  95657. }
  95658. else {
  95659. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  95660. this._onBeforeParticlesRenderingObserver = null;
  95661. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  95662. this._onAfterParticlesRenderingObserver = null;
  95663. }
  95664. },
  95665. enumerable: true,
  95666. configurable: true
  95667. });
  95668. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  95669. /**
  95670. * Gets the perf counter used for sprites render time
  95671. */
  95672. get: function () {
  95673. return this._spritesRenderTime;
  95674. },
  95675. enumerable: true,
  95676. configurable: true
  95677. });
  95678. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  95679. /**
  95680. * Gets the sprites render time capture status
  95681. */
  95682. get: function () {
  95683. return this._captureSpritesRenderTime;
  95684. },
  95685. /**
  95686. * Enable or disable the sprites render time capture
  95687. */
  95688. set: function (value) {
  95689. var _this = this;
  95690. if (value === this._captureSpritesRenderTime) {
  95691. return;
  95692. }
  95693. this._captureSpritesRenderTime = value;
  95694. if (value) {
  95695. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  95696. BABYLON.Tools.StartPerformanceCounter("Sprites");
  95697. _this._spritesRenderTime.beginMonitoring();
  95698. });
  95699. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  95700. BABYLON.Tools.EndPerformanceCounter("Sprites");
  95701. _this._spritesRenderTime.endMonitoring(false);
  95702. });
  95703. }
  95704. else {
  95705. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  95706. this._onBeforeSpritesRenderingObserver = null;
  95707. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  95708. this._onAfterSpritesRenderingObserver = null;
  95709. }
  95710. },
  95711. enumerable: true,
  95712. configurable: true
  95713. });
  95714. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  95715. /**
  95716. * Gets the perf counter used for physics time
  95717. */
  95718. get: function () {
  95719. return this._physicsTime;
  95720. },
  95721. enumerable: true,
  95722. configurable: true
  95723. });
  95724. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  95725. /**
  95726. * Gets the physics time capture status
  95727. */
  95728. get: function () {
  95729. return this._capturePhysicsTime;
  95730. },
  95731. /**
  95732. * Enable or disable the physics time capture
  95733. */
  95734. set: function (value) {
  95735. var _this = this;
  95736. if (value === this._capturePhysicsTime) {
  95737. return;
  95738. }
  95739. this._capturePhysicsTime = value;
  95740. if (value) {
  95741. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  95742. BABYLON.Tools.StartPerformanceCounter("Physics");
  95743. _this._physicsTime.beginMonitoring();
  95744. });
  95745. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  95746. BABYLON.Tools.EndPerformanceCounter("Physics");
  95747. _this._physicsTime.endMonitoring();
  95748. });
  95749. }
  95750. else {
  95751. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  95752. this._onBeforePhysicsObserver = null;
  95753. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  95754. this._onAfterPhysicsObserver = null;
  95755. }
  95756. },
  95757. enumerable: true,
  95758. configurable: true
  95759. });
  95760. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  95761. /**
  95762. * Gets the perf counter used for animations time
  95763. */
  95764. get: function () {
  95765. return this._animationsTime;
  95766. },
  95767. enumerable: true,
  95768. configurable: true
  95769. });
  95770. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  95771. /**
  95772. * Gets the animations time capture status
  95773. */
  95774. get: function () {
  95775. return this._captureAnimationsTime;
  95776. },
  95777. /**
  95778. * Enable or disable the animations time capture
  95779. */
  95780. set: function (value) {
  95781. var _this = this;
  95782. if (value === this._captureAnimationsTime) {
  95783. return;
  95784. }
  95785. this._captureAnimationsTime = value;
  95786. if (value) {
  95787. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  95788. _this._animationsTime.endMonitoring();
  95789. });
  95790. }
  95791. else {
  95792. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  95793. this._onAfterAnimationsObserver = null;
  95794. }
  95795. },
  95796. enumerable: true,
  95797. configurable: true
  95798. });
  95799. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  95800. /**
  95801. * Gets the perf counter used for frame time capture
  95802. */
  95803. get: function () {
  95804. return this._frameTime;
  95805. },
  95806. enumerable: true,
  95807. configurable: true
  95808. });
  95809. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  95810. /**
  95811. * Gets the frame time capture status
  95812. */
  95813. get: function () {
  95814. return this._captureFrameTime;
  95815. },
  95816. /**
  95817. * Enable or disable the frame time capture
  95818. */
  95819. set: function (value) {
  95820. this._captureFrameTime = value;
  95821. },
  95822. enumerable: true,
  95823. configurable: true
  95824. });
  95825. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  95826. /**
  95827. * Gets the perf counter used for inter-frames time capture
  95828. */
  95829. get: function () {
  95830. return this._interFrameTime;
  95831. },
  95832. enumerable: true,
  95833. configurable: true
  95834. });
  95835. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  95836. /**
  95837. * Gets the inter-frames time capture status
  95838. */
  95839. get: function () {
  95840. return this._captureInterFrameTime;
  95841. },
  95842. /**
  95843. * Enable or disable the inter-frames time capture
  95844. */
  95845. set: function (value) {
  95846. this._captureInterFrameTime = value;
  95847. },
  95848. enumerable: true,
  95849. configurable: true
  95850. });
  95851. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  95852. /**
  95853. * Gets the perf counter used for render time capture
  95854. */
  95855. get: function () {
  95856. return this._renderTime;
  95857. },
  95858. enumerable: true,
  95859. configurable: true
  95860. });
  95861. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  95862. /**
  95863. * Gets the render time capture status
  95864. */
  95865. get: function () {
  95866. return this._captureRenderTime;
  95867. },
  95868. /**
  95869. * Enable or disable the render time capture
  95870. */
  95871. set: function (value) {
  95872. var _this = this;
  95873. if (value === this._captureRenderTime) {
  95874. return;
  95875. }
  95876. this._captureRenderTime = value;
  95877. if (value) {
  95878. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  95879. _this._renderTime.beginMonitoring();
  95880. BABYLON.Tools.StartPerformanceCounter("Main render");
  95881. });
  95882. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  95883. _this._renderTime.endMonitoring(false);
  95884. BABYLON.Tools.EndPerformanceCounter("Main render");
  95885. });
  95886. }
  95887. else {
  95888. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  95889. this._onBeforeDrawPhaseObserver = null;
  95890. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  95891. this._onAfterDrawPhaseObserver = null;
  95892. }
  95893. },
  95894. enumerable: true,
  95895. configurable: true
  95896. });
  95897. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  95898. /**
  95899. * Gets the perf counter used for draw calls
  95900. */
  95901. get: function () {
  95902. return this.scene.getEngine()._drawCalls;
  95903. },
  95904. enumerable: true,
  95905. configurable: true
  95906. });
  95907. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  95908. /**
  95909. * Gets the perf counter used for texture collisions
  95910. */
  95911. get: function () {
  95912. return this.scene.getEngine()._textureCollisions;
  95913. },
  95914. enumerable: true,
  95915. configurable: true
  95916. });
  95917. SceneInstrumentation.prototype.dispose = function () {
  95918. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  95919. this._onAfterRenderObserver = null;
  95920. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  95921. this._onBeforeActiveMeshesEvaluationObserver = null;
  95922. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  95923. this._onAfterActiveMeshesEvaluationObserver = null;
  95924. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  95925. this._onBeforeRenderTargetsRenderObserver = null;
  95926. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  95927. this._onAfterRenderTargetsRenderObserver = null;
  95928. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  95929. this._onBeforeAnimationsObserver = null;
  95930. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  95931. this._onBeforeParticlesRenderingObserver = null;
  95932. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  95933. this._onAfterParticlesRenderingObserver = null;
  95934. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  95935. this._onBeforeSpritesRenderingObserver = null;
  95936. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  95937. this._onAfterSpritesRenderingObserver = null;
  95938. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  95939. this._onBeforeDrawPhaseObserver = null;
  95940. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  95941. this._onAfterDrawPhaseObserver = null;
  95942. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  95943. this._onBeforePhysicsObserver = null;
  95944. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  95945. this._onAfterPhysicsObserver = null;
  95946. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  95947. this._onAfterAnimationsObserver = null;
  95948. this.scene = null;
  95949. };
  95950. return SceneInstrumentation;
  95951. }());
  95952. BABYLON.SceneInstrumentation = SceneInstrumentation;
  95953. })(BABYLON || (BABYLON = {}));
  95954. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  95955. var BABYLON;
  95956. (function (BABYLON) {
  95957. /**
  95958. * @hidden
  95959. **/
  95960. var _TimeToken = /** @class */ (function () {
  95961. function _TimeToken() {
  95962. this._timeElapsedQueryEnded = false;
  95963. }
  95964. return _TimeToken;
  95965. }());
  95966. BABYLON._TimeToken = _TimeToken;
  95967. })(BABYLON || (BABYLON = {}));
  95968. //# sourceMappingURL=babylon.timeToken.js.map
  95969. var BABYLON;
  95970. (function (BABYLON) {
  95971. /**
  95972. * Background material defines definition.
  95973. * @hidden Mainly internal Use
  95974. */
  95975. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  95976. __extends(BackgroundMaterialDefines, _super);
  95977. /**
  95978. * Constructor of the defines.
  95979. */
  95980. function BackgroundMaterialDefines() {
  95981. var _this = _super.call(this) || this;
  95982. /**
  95983. * True if the diffuse texture is in use.
  95984. */
  95985. _this.DIFFUSE = false;
  95986. /**
  95987. * The direct UV channel to use.
  95988. */
  95989. _this.DIFFUSEDIRECTUV = 0;
  95990. /**
  95991. * True if the diffuse texture is in gamma space.
  95992. */
  95993. _this.GAMMADIFFUSE = false;
  95994. /**
  95995. * True if the diffuse texture has opacity in the alpha channel.
  95996. */
  95997. _this.DIFFUSEHASALPHA = false;
  95998. /**
  95999. * True if you want the material to fade to transparent at grazing angle.
  96000. */
  96001. _this.OPACITYFRESNEL = false;
  96002. /**
  96003. * True if an extra blur needs to be added in the reflection.
  96004. */
  96005. _this.REFLECTIONBLUR = false;
  96006. /**
  96007. * True if you want the material to fade to reflection at grazing angle.
  96008. */
  96009. _this.REFLECTIONFRESNEL = false;
  96010. /**
  96011. * True if you want the material to falloff as far as you move away from the scene center.
  96012. */
  96013. _this.REFLECTIONFALLOFF = false;
  96014. /**
  96015. * False if the current Webgl implementation does not support the texture lod extension.
  96016. */
  96017. _this.TEXTURELODSUPPORT = false;
  96018. /**
  96019. * True to ensure the data are premultiplied.
  96020. */
  96021. _this.PREMULTIPLYALPHA = false;
  96022. /**
  96023. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  96024. */
  96025. _this.USERGBCOLOR = false;
  96026. /**
  96027. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  96028. * stays aligned with the desired configuration.
  96029. */
  96030. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  96031. /**
  96032. * True to add noise in order to reduce the banding effect.
  96033. */
  96034. _this.NOISE = false;
  96035. /**
  96036. * is the reflection texture in BGR color scheme?
  96037. * Mainly used to solve a bug in ios10 video tag
  96038. */
  96039. _this.REFLECTIONBGR = false;
  96040. _this.IMAGEPROCESSING = false;
  96041. _this.VIGNETTE = false;
  96042. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  96043. _this.VIGNETTEBLENDMODEOPAQUE = false;
  96044. _this.TONEMAPPING = false;
  96045. _this.CONTRAST = false;
  96046. _this.COLORCURVES = false;
  96047. _this.COLORGRADING = false;
  96048. _this.COLORGRADING3D = false;
  96049. _this.SAMPLER3DGREENDEPTH = false;
  96050. _this.SAMPLER3DBGRMAP = false;
  96051. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  96052. _this.EXPOSURE = false;
  96053. // Reflection.
  96054. _this.REFLECTION = false;
  96055. _this.REFLECTIONMAP_3D = false;
  96056. _this.REFLECTIONMAP_SPHERICAL = false;
  96057. _this.REFLECTIONMAP_PLANAR = false;
  96058. _this.REFLECTIONMAP_CUBIC = false;
  96059. _this.REFLECTIONMAP_PROJECTION = false;
  96060. _this.REFLECTIONMAP_SKYBOX = false;
  96061. _this.REFLECTIONMAP_EXPLICIT = false;
  96062. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  96063. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  96064. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  96065. _this.INVERTCUBICMAP = false;
  96066. _this.REFLECTIONMAP_OPPOSITEZ = false;
  96067. _this.LODINREFLECTIONALPHA = false;
  96068. _this.GAMMAREFLECTION = false;
  96069. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  96070. // Default BJS.
  96071. _this.MAINUV1 = false;
  96072. _this.MAINUV2 = false;
  96073. _this.UV1 = false;
  96074. _this.UV2 = false;
  96075. _this.CLIPPLANE = false;
  96076. _this.POINTSIZE = false;
  96077. _this.FOG = false;
  96078. _this.NORMAL = false;
  96079. _this.NUM_BONE_INFLUENCERS = 0;
  96080. _this.BonesPerMesh = 0;
  96081. _this.INSTANCES = false;
  96082. _this.SHADOWFLOAT = false;
  96083. _this.rebuild();
  96084. return _this;
  96085. }
  96086. return BackgroundMaterialDefines;
  96087. }(BABYLON.MaterialDefines));
  96088. /**
  96089. * Background material used to create an efficient environement around your scene.
  96090. */
  96091. var BackgroundMaterial = /** @class */ (function (_super) {
  96092. __extends(BackgroundMaterial, _super);
  96093. /**
  96094. * Instantiates a Background Material in the given scene
  96095. * @param name The friendly name of the material
  96096. * @param scene The scene to add the material to
  96097. */
  96098. function BackgroundMaterial(name, scene) {
  96099. var _this = _super.call(this, name, scene) || this;
  96100. /**
  96101. * Key light Color (multiply against the environement texture)
  96102. */
  96103. _this.primaryColor = BABYLON.Color3.White();
  96104. _this._primaryColorShadowLevel = 0;
  96105. _this._primaryColorHighlightLevel = 0;
  96106. /**
  96107. * Reflection Texture used in the material.
  96108. * Should be author in a specific way for the best result (refer to the documentation).
  96109. */
  96110. _this.reflectionTexture = null;
  96111. /**
  96112. * Reflection Texture level of blur.
  96113. *
  96114. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  96115. * texture twice.
  96116. */
  96117. _this.reflectionBlur = 0;
  96118. /**
  96119. * Diffuse Texture used in the material.
  96120. * Should be author in a specific way for the best result (refer to the documentation).
  96121. */
  96122. _this.diffuseTexture = null;
  96123. _this._shadowLights = null;
  96124. /**
  96125. * Specify the list of lights casting shadow on the material.
  96126. * All scene shadow lights will be included if null.
  96127. */
  96128. _this.shadowLights = null;
  96129. /**
  96130. * Helps adjusting the shadow to a softer level if required.
  96131. * 0 means black shadows and 1 means no shadows.
  96132. */
  96133. _this.shadowLevel = 0;
  96134. /**
  96135. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  96136. * It is usually zero but might be interesting to modify according to your setup.
  96137. */
  96138. _this.sceneCenter = BABYLON.Vector3.Zero();
  96139. /**
  96140. * This helps specifying that the material is falling off to the sky box at grazing angle.
  96141. * This helps ensuring a nice transition when the camera goes under the ground.
  96142. */
  96143. _this.opacityFresnel = true;
  96144. /**
  96145. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  96146. * This helps adding a mirror texture on the ground.
  96147. */
  96148. _this.reflectionFresnel = false;
  96149. /**
  96150. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  96151. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  96152. */
  96153. _this.reflectionFalloffDistance = 0.0;
  96154. /**
  96155. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  96156. */
  96157. _this.reflectionAmount = 1.0;
  96158. /**
  96159. * This specifies the weight of the reflection at grazing angle.
  96160. */
  96161. _this.reflectionReflectance0 = 0.05;
  96162. /**
  96163. * This specifies the weight of the reflection at a perpendicular point of view.
  96164. */
  96165. _this.reflectionReflectance90 = 0.5;
  96166. /**
  96167. * Helps to directly use the maps channels instead of their level.
  96168. */
  96169. _this.useRGBColor = true;
  96170. /**
  96171. * This helps reducing the banding effect that could occur on the background.
  96172. */
  96173. _this.enableNoise = false;
  96174. _this._fovMultiplier = 1.0;
  96175. /**
  96176. * Enable the FOV adjustment feature controlled by fovMultiplier.
  96177. */
  96178. _this.useEquirectangularFOV = false;
  96179. _this._maxSimultaneousLights = 4;
  96180. /**
  96181. * Number of Simultaneous lights allowed on the material.
  96182. */
  96183. _this.maxSimultaneousLights = 4;
  96184. /**
  96185. * Keep track of the image processing observer to allow dispose and replace.
  96186. */
  96187. _this._imageProcessingObserver = null;
  96188. /**
  96189. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  96190. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  96191. */
  96192. _this.switchToBGR = false;
  96193. // Temp values kept as cache in the material.
  96194. _this._renderTargets = new BABYLON.SmartArray(16);
  96195. _this._reflectionControls = BABYLON.Vector4.Zero();
  96196. _this._white = BABYLON.Color3.White();
  96197. _this._primaryShadowColor = BABYLON.Color3.Black();
  96198. _this._primaryHighlightColor = BABYLON.Color3.Black();
  96199. // Setup the default processing configuration to the scene.
  96200. _this._attachImageProcessingConfiguration(null);
  96201. _this.getRenderTargetTextures = function () {
  96202. _this._renderTargets.reset();
  96203. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  96204. _this._renderTargets.push(_this._diffuseTexture);
  96205. }
  96206. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  96207. _this._renderTargets.push(_this._reflectionTexture);
  96208. }
  96209. return _this._renderTargets;
  96210. };
  96211. return _this;
  96212. }
  96213. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  96214. /**
  96215. * Experimental Internal Use Only.
  96216. *
  96217. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  96218. * This acts as a helper to set the primary color to a more "human friendly" value.
  96219. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  96220. * output color as close as possible from the chosen value.
  96221. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  96222. * part of lighting setup.)
  96223. */
  96224. get: function () {
  96225. return this.__perceptualColor;
  96226. },
  96227. set: function (value) {
  96228. this.__perceptualColor = value;
  96229. this._computePrimaryColorFromPerceptualColor();
  96230. this._markAllSubMeshesAsLightsDirty();
  96231. },
  96232. enumerable: true,
  96233. configurable: true
  96234. });
  96235. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  96236. /**
  96237. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  96238. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  96239. */
  96240. get: function () {
  96241. return this._primaryColorShadowLevel;
  96242. },
  96243. set: function (value) {
  96244. this._primaryColorShadowLevel = value;
  96245. this._computePrimaryColors();
  96246. this._markAllSubMeshesAsLightsDirty();
  96247. },
  96248. enumerable: true,
  96249. configurable: true
  96250. });
  96251. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  96252. /**
  96253. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  96254. * The primary color is used at the level chosen to define what the white area would look.
  96255. */
  96256. get: function () {
  96257. return this._primaryColorHighlightLevel;
  96258. },
  96259. set: function (value) {
  96260. this._primaryColorHighlightLevel = value;
  96261. this._computePrimaryColors();
  96262. this._markAllSubMeshesAsLightsDirty();
  96263. },
  96264. enumerable: true,
  96265. configurable: true
  96266. });
  96267. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  96268. /**
  96269. * Sets the reflection reflectance fresnel values according to the default standard
  96270. * empirically know to work well :-)
  96271. */
  96272. set: function (value) {
  96273. var reflectionWeight = value;
  96274. if (reflectionWeight < 0.5) {
  96275. reflectionWeight = reflectionWeight * 2.0;
  96276. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  96277. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  96278. }
  96279. else {
  96280. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  96281. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  96282. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  96283. }
  96284. },
  96285. enumerable: true,
  96286. configurable: true
  96287. });
  96288. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  96289. /**
  96290. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  96291. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  96292. * Recommended to be keep at 1.0 except for special cases.
  96293. */
  96294. get: function () {
  96295. return this._fovMultiplier;
  96296. },
  96297. set: function (value) {
  96298. if (isNaN(value)) {
  96299. value = 1.0;
  96300. }
  96301. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  96302. },
  96303. enumerable: true,
  96304. configurable: true
  96305. });
  96306. /**
  96307. * Attaches a new image processing configuration to the PBR Material.
  96308. * @param configuration (if null the scene configuration will be use)
  96309. */
  96310. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  96311. var _this = this;
  96312. if (configuration === this._imageProcessingConfiguration) {
  96313. return;
  96314. }
  96315. // Detaches observer.
  96316. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  96317. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  96318. }
  96319. // Pick the scene configuration if needed.
  96320. if (!configuration) {
  96321. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  96322. }
  96323. else {
  96324. this._imageProcessingConfiguration = configuration;
  96325. }
  96326. // Attaches observer.
  96327. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  96328. _this._computePrimaryColorFromPerceptualColor();
  96329. _this._markAllSubMeshesAsImageProcessingDirty();
  96330. });
  96331. };
  96332. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  96333. /**
  96334. * Gets the image processing configuration used either in this material.
  96335. */
  96336. get: function () {
  96337. return this._imageProcessingConfiguration;
  96338. },
  96339. /**
  96340. * Sets the Default image processing configuration used either in the this material.
  96341. *
  96342. * If sets to null, the scene one is in use.
  96343. */
  96344. set: function (value) {
  96345. this._attachImageProcessingConfiguration(value);
  96346. // Ensure the effect will be rebuilt.
  96347. this._markAllSubMeshesAsTexturesDirty();
  96348. },
  96349. enumerable: true,
  96350. configurable: true
  96351. });
  96352. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  96353. /**
  96354. * Gets wether the color curves effect is enabled.
  96355. */
  96356. get: function () {
  96357. return this.imageProcessingConfiguration.colorCurvesEnabled;
  96358. },
  96359. /**
  96360. * Sets wether the color curves effect is enabled.
  96361. */
  96362. set: function (value) {
  96363. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  96364. },
  96365. enumerable: true,
  96366. configurable: true
  96367. });
  96368. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  96369. /**
  96370. * Gets wether the color grading effect is enabled.
  96371. */
  96372. get: function () {
  96373. return this.imageProcessingConfiguration.colorGradingEnabled;
  96374. },
  96375. /**
  96376. * Gets wether the color grading effect is enabled.
  96377. */
  96378. set: function (value) {
  96379. this.imageProcessingConfiguration.colorGradingEnabled = value;
  96380. },
  96381. enumerable: true,
  96382. configurable: true
  96383. });
  96384. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  96385. /**
  96386. * Gets wether tonemapping is enabled or not.
  96387. */
  96388. get: function () {
  96389. return this._imageProcessingConfiguration.toneMappingEnabled;
  96390. },
  96391. /**
  96392. * Sets wether tonemapping is enabled or not
  96393. */
  96394. set: function (value) {
  96395. this._imageProcessingConfiguration.toneMappingEnabled = value;
  96396. },
  96397. enumerable: true,
  96398. configurable: true
  96399. });
  96400. ;
  96401. ;
  96402. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  96403. /**
  96404. * The camera exposure used on this material.
  96405. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  96406. * This corresponds to a photographic exposure.
  96407. */
  96408. get: function () {
  96409. return this._imageProcessingConfiguration.exposure;
  96410. },
  96411. /**
  96412. * The camera exposure used on this material.
  96413. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  96414. * This corresponds to a photographic exposure.
  96415. */
  96416. set: function (value) {
  96417. this._imageProcessingConfiguration.exposure = value;
  96418. },
  96419. enumerable: true,
  96420. configurable: true
  96421. });
  96422. ;
  96423. ;
  96424. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  96425. /**
  96426. * Gets The camera contrast used on this material.
  96427. */
  96428. get: function () {
  96429. return this._imageProcessingConfiguration.contrast;
  96430. },
  96431. /**
  96432. * Sets The camera contrast used on this material.
  96433. */
  96434. set: function (value) {
  96435. this._imageProcessingConfiguration.contrast = value;
  96436. },
  96437. enumerable: true,
  96438. configurable: true
  96439. });
  96440. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  96441. /**
  96442. * Gets the Color Grading 2D Lookup Texture.
  96443. */
  96444. get: function () {
  96445. return this._imageProcessingConfiguration.colorGradingTexture;
  96446. },
  96447. /**
  96448. * Sets the Color Grading 2D Lookup Texture.
  96449. */
  96450. set: function (value) {
  96451. this.imageProcessingConfiguration.colorGradingTexture = value;
  96452. },
  96453. enumerable: true,
  96454. configurable: true
  96455. });
  96456. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  96457. /**
  96458. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  96459. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  96460. * 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;
  96461. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  96462. */
  96463. get: function () {
  96464. return this.imageProcessingConfiguration.colorCurves;
  96465. },
  96466. /**
  96467. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  96468. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  96469. * 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;
  96470. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  96471. */
  96472. set: function (value) {
  96473. this.imageProcessingConfiguration.colorCurves = value;
  96474. },
  96475. enumerable: true,
  96476. configurable: true
  96477. });
  96478. /**
  96479. * The entire material has been created in order to prevent overdraw.
  96480. * @returns false
  96481. */
  96482. BackgroundMaterial.prototype.needAlphaTesting = function () {
  96483. return true;
  96484. };
  96485. /**
  96486. * The entire material has been created in order to prevent overdraw.
  96487. * @returns true if blending is enable
  96488. */
  96489. BackgroundMaterial.prototype.needAlphaBlending = function () {
  96490. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  96491. };
  96492. /**
  96493. * Checks wether the material is ready to be rendered for a given mesh.
  96494. * @param mesh The mesh to render
  96495. * @param subMesh The submesh to check against
  96496. * @param useInstances Specify wether or not the material is used with instances
  96497. * @returns true if all the dependencies are ready (Textures, Effects...)
  96498. */
  96499. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  96500. var _this = this;
  96501. if (useInstances === void 0) { useInstances = false; }
  96502. if (subMesh.effect && this.isFrozen) {
  96503. if (this._wasPreviouslyReady) {
  96504. return true;
  96505. }
  96506. }
  96507. if (!subMesh._materialDefines) {
  96508. subMesh._materialDefines = new BackgroundMaterialDefines();
  96509. }
  96510. var scene = this.getScene();
  96511. var defines = subMesh._materialDefines;
  96512. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  96513. if (defines._renderId === scene.getRenderId()) {
  96514. return true;
  96515. }
  96516. }
  96517. var engine = scene.getEngine();
  96518. // Lights
  96519. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  96520. defines._needNormals = true;
  96521. // Textures
  96522. if (defines._areTexturesDirty) {
  96523. defines._needUVs = false;
  96524. if (scene.texturesEnabled) {
  96525. if (scene.getEngine().getCaps().textureLOD) {
  96526. defines.TEXTURELODSUPPORT = true;
  96527. }
  96528. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  96529. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  96530. return false;
  96531. }
  96532. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  96533. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  96534. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  96535. defines.OPACITYFRESNEL = this._opacityFresnel;
  96536. }
  96537. else {
  96538. defines.DIFFUSE = false;
  96539. defines.DIFFUSEHASALPHA = false;
  96540. defines.GAMMADIFFUSE = false;
  96541. defines.OPACITYFRESNEL = false;
  96542. }
  96543. var reflectionTexture = this._reflectionTexture;
  96544. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  96545. if (!reflectionTexture.isReadyOrNotBlocking()) {
  96546. return false;
  96547. }
  96548. defines.REFLECTION = true;
  96549. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  96550. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  96551. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  96552. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  96553. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  96554. defines.REFLECTIONBGR = this.switchToBGR;
  96555. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  96556. defines.INVERTCUBICMAP = true;
  96557. }
  96558. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  96559. switch (reflectionTexture.coordinatesMode) {
  96560. case BABYLON.Texture.EXPLICIT_MODE:
  96561. defines.REFLECTIONMAP_EXPLICIT = true;
  96562. break;
  96563. case BABYLON.Texture.PLANAR_MODE:
  96564. defines.REFLECTIONMAP_PLANAR = true;
  96565. break;
  96566. case BABYLON.Texture.PROJECTION_MODE:
  96567. defines.REFLECTIONMAP_PROJECTION = true;
  96568. break;
  96569. case BABYLON.Texture.SKYBOX_MODE:
  96570. defines.REFLECTIONMAP_SKYBOX = true;
  96571. break;
  96572. case BABYLON.Texture.SPHERICAL_MODE:
  96573. defines.REFLECTIONMAP_SPHERICAL = true;
  96574. break;
  96575. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  96576. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  96577. break;
  96578. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  96579. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  96580. break;
  96581. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  96582. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  96583. break;
  96584. case BABYLON.Texture.CUBIC_MODE:
  96585. case BABYLON.Texture.INVCUBIC_MODE:
  96586. default:
  96587. defines.REFLECTIONMAP_CUBIC = true;
  96588. break;
  96589. }
  96590. if (this.reflectionFresnel) {
  96591. defines.REFLECTIONFRESNEL = true;
  96592. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  96593. this._reflectionControls.x = this.reflectionAmount;
  96594. this._reflectionControls.y = this.reflectionReflectance0;
  96595. this._reflectionControls.z = this.reflectionReflectance90;
  96596. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  96597. }
  96598. else {
  96599. defines.REFLECTIONFRESNEL = false;
  96600. defines.REFLECTIONFALLOFF = false;
  96601. }
  96602. }
  96603. else {
  96604. defines.REFLECTION = false;
  96605. defines.REFLECTIONFRESNEL = false;
  96606. defines.REFLECTIONFALLOFF = false;
  96607. defines.REFLECTIONBLUR = false;
  96608. defines.REFLECTIONMAP_3D = false;
  96609. defines.REFLECTIONMAP_SPHERICAL = false;
  96610. defines.REFLECTIONMAP_PLANAR = false;
  96611. defines.REFLECTIONMAP_CUBIC = false;
  96612. defines.REFLECTIONMAP_PROJECTION = false;
  96613. defines.REFLECTIONMAP_SKYBOX = false;
  96614. defines.REFLECTIONMAP_EXPLICIT = false;
  96615. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  96616. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  96617. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  96618. defines.INVERTCUBICMAP = false;
  96619. defines.REFLECTIONMAP_OPPOSITEZ = false;
  96620. defines.LODINREFLECTIONALPHA = false;
  96621. defines.GAMMAREFLECTION = false;
  96622. }
  96623. }
  96624. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  96625. defines.USERGBCOLOR = this._useRGBColor;
  96626. defines.NOISE = this._enableNoise;
  96627. }
  96628. if (defines._areLightsDirty) {
  96629. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  96630. }
  96631. if (defines._areImageProcessingDirty) {
  96632. if (!this._imageProcessingConfiguration.isReady()) {
  96633. return false;
  96634. }
  96635. this._imageProcessingConfiguration.prepareDefines(defines);
  96636. }
  96637. // Misc.
  96638. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  96639. // Values that need to be evaluated on every frame
  96640. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  96641. // Attribs
  96642. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  96643. if (mesh) {
  96644. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  96645. mesh.createNormals(true);
  96646. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  96647. }
  96648. }
  96649. }
  96650. // Get correct effect
  96651. if (defines.isDirty) {
  96652. defines.markAsProcessed();
  96653. scene.resetCachedMaterial();
  96654. // Fallbacks
  96655. var fallbacks = new BABYLON.EffectFallbacks();
  96656. if (defines.FOG) {
  96657. fallbacks.addFallback(0, "FOG");
  96658. }
  96659. if (defines.POINTSIZE) {
  96660. fallbacks.addFallback(1, "POINTSIZE");
  96661. }
  96662. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  96663. if (defines.NUM_BONE_INFLUENCERS > 0) {
  96664. fallbacks.addCPUSkinningFallback(0, mesh);
  96665. }
  96666. //Attributes
  96667. var attribs = [BABYLON.VertexBuffer.PositionKind];
  96668. if (defines.NORMAL) {
  96669. attribs.push(BABYLON.VertexBuffer.NormalKind);
  96670. }
  96671. if (defines.UV1) {
  96672. attribs.push(BABYLON.VertexBuffer.UVKind);
  96673. }
  96674. if (defines.UV2) {
  96675. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  96676. }
  96677. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  96678. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  96679. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  96680. "vFogInfos", "vFogColor", "pointSize",
  96681. "vClipPlane", "mBones",
  96682. "vPrimaryColor", "vPrimaryColorShadow",
  96683. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  96684. "shadowLevel", "alpha",
  96685. "vBackgroundCenter", "vReflectionControl",
  96686. "vDiffuseInfos", "diffuseMatrix",
  96687. ];
  96688. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  96689. var uniformBuffers = ["Material", "Scene"];
  96690. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  96691. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  96692. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  96693. uniformsNames: uniforms,
  96694. uniformBuffersNames: uniformBuffers,
  96695. samplers: samplers,
  96696. defines: defines,
  96697. maxSimultaneousLights: this._maxSimultaneousLights
  96698. });
  96699. var onCompiled = function (effect) {
  96700. if (_this.onCompiled) {
  96701. _this.onCompiled(effect);
  96702. }
  96703. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  96704. };
  96705. var join = defines.toString();
  96706. subMesh.setEffect(scene.getEngine().createEffect("background", {
  96707. attributes: attribs,
  96708. uniformsNames: uniforms,
  96709. uniformBuffersNames: uniformBuffers,
  96710. samplers: samplers,
  96711. defines: join,
  96712. fallbacks: fallbacks,
  96713. onCompiled: onCompiled,
  96714. onError: this.onError,
  96715. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  96716. }, engine), defines);
  96717. this.buildUniformLayout();
  96718. }
  96719. if (!subMesh.effect || !subMesh.effect.isReady()) {
  96720. return false;
  96721. }
  96722. defines._renderId = scene.getRenderId();
  96723. this._wasPreviouslyReady = true;
  96724. return true;
  96725. };
  96726. /**
  96727. * Compute the primary color according to the chosen perceptual color.
  96728. */
  96729. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  96730. if (!this.__perceptualColor) {
  96731. return;
  96732. }
  96733. this._primaryColor.copyFrom(this.__perceptualColor);
  96734. // Revert gamma space.
  96735. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  96736. // Revert image processing configuration.
  96737. if (this._imageProcessingConfiguration) {
  96738. // Revert Exposure.
  96739. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  96740. }
  96741. this._computePrimaryColors();
  96742. };
  96743. /**
  96744. * Compute the highlights and shadow colors according to their chosen levels.
  96745. */
  96746. BackgroundMaterial.prototype._computePrimaryColors = function () {
  96747. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  96748. return;
  96749. }
  96750. // Find the highlight color based on the configuration.
  96751. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  96752. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  96753. // Find the shadow color based on the configuration.
  96754. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  96755. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  96756. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  96757. };
  96758. /**
  96759. * Build the uniform buffer used in the material.
  96760. */
  96761. BackgroundMaterial.prototype.buildUniformLayout = function () {
  96762. // Order is important !
  96763. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  96764. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  96765. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  96766. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  96767. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  96768. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  96769. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  96770. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  96771. this._uniformBuffer.addUniform("pointSize", 1);
  96772. this._uniformBuffer.addUniform("shadowLevel", 1);
  96773. this._uniformBuffer.addUniform("alpha", 1);
  96774. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  96775. this._uniformBuffer.addUniform("vReflectionControl", 4);
  96776. this._uniformBuffer.create();
  96777. };
  96778. /**
  96779. * Unbind the material.
  96780. */
  96781. BackgroundMaterial.prototype.unbind = function () {
  96782. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  96783. this._uniformBuffer.setTexture("diffuseSampler", null);
  96784. }
  96785. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  96786. this._uniformBuffer.setTexture("reflectionSampler", null);
  96787. }
  96788. _super.prototype.unbind.call(this);
  96789. };
  96790. /**
  96791. * Bind only the world matrix to the material.
  96792. * @param world The world matrix to bind.
  96793. */
  96794. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  96795. this._activeEffect.setMatrix("world", world);
  96796. };
  96797. /**
  96798. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  96799. * @param world The world matrix to bind.
  96800. * @param subMesh The submesh to bind for.
  96801. */
  96802. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  96803. var scene = this.getScene();
  96804. var defines = subMesh._materialDefines;
  96805. if (!defines) {
  96806. return;
  96807. }
  96808. var effect = subMesh.effect;
  96809. if (!effect) {
  96810. return;
  96811. }
  96812. this._activeEffect = effect;
  96813. // Matrices
  96814. this.bindOnlyWorldMatrix(world);
  96815. // Bones
  96816. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  96817. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  96818. if (mustRebind) {
  96819. this._uniformBuffer.bindToEffect(effect, "Material");
  96820. this.bindViewProjection(effect);
  96821. var reflectionTexture = this._reflectionTexture;
  96822. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  96823. // Texture uniforms
  96824. if (scene.texturesEnabled) {
  96825. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  96826. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  96827. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  96828. }
  96829. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  96830. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  96831. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  96832. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  96833. }
  96834. }
  96835. if (this.shadowLevel > 0) {
  96836. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  96837. }
  96838. this._uniformBuffer.updateFloat("alpha", this.alpha);
  96839. // Point size
  96840. if (this.pointsCloud) {
  96841. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  96842. }
  96843. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  96844. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  96845. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  96846. }
  96847. else {
  96848. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  96849. }
  96850. }
  96851. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  96852. // Textures
  96853. if (scene.texturesEnabled) {
  96854. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  96855. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  96856. }
  96857. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  96858. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  96859. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  96860. }
  96861. else if (!defines.REFLECTIONBLUR) {
  96862. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  96863. }
  96864. else {
  96865. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  96866. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  96867. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  96868. }
  96869. if (defines.REFLECTIONFRESNEL) {
  96870. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  96871. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  96872. }
  96873. }
  96874. }
  96875. // Clip plane
  96876. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  96877. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  96878. }
  96879. if (mustRebind || !this.isFrozen) {
  96880. if (scene.lightsEnabled) {
  96881. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  96882. }
  96883. // View
  96884. this.bindView(effect);
  96885. // Fog
  96886. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  96887. // image processing
  96888. this._imageProcessingConfiguration.bind(this._activeEffect);
  96889. }
  96890. this._uniformBuffer.update();
  96891. this._afterBind(mesh);
  96892. };
  96893. /**
  96894. * Dispose the material.
  96895. * @param forceDisposeEffect Force disposal of the associated effect.
  96896. * @param forceDisposeTextures Force disposal of the associated textures.
  96897. */
  96898. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  96899. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  96900. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  96901. if (forceDisposeTextures) {
  96902. if (this.diffuseTexture) {
  96903. this.diffuseTexture.dispose();
  96904. }
  96905. if (this.reflectionTexture) {
  96906. this.reflectionTexture.dispose();
  96907. }
  96908. }
  96909. this._renderTargets.dispose();
  96910. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  96911. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  96912. }
  96913. _super.prototype.dispose.call(this, forceDisposeEffect);
  96914. };
  96915. /**
  96916. * Clones the material.
  96917. * @param name The cloned name.
  96918. * @returns The cloned material.
  96919. */
  96920. BackgroundMaterial.prototype.clone = function (name) {
  96921. var _this = this;
  96922. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  96923. };
  96924. /**
  96925. * Serializes the current material to its JSON representation.
  96926. * @returns The JSON representation.
  96927. */
  96928. BackgroundMaterial.prototype.serialize = function () {
  96929. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  96930. serializationObject.customType = "BABYLON.BackgroundMaterial";
  96931. return serializationObject;
  96932. };
  96933. /**
  96934. * Gets the class name of the material
  96935. * @returns "BackgroundMaterial"
  96936. */
  96937. BackgroundMaterial.prototype.getClassName = function () {
  96938. return "BackgroundMaterial";
  96939. };
  96940. /**
  96941. * Parse a JSON input to create back a background material.
  96942. * @param source The JSON data to parse
  96943. * @param scene The scene to create the parsed material in
  96944. * @param rootUrl The root url of the assets the material depends upon
  96945. * @returns the instantiated BackgroundMaterial.
  96946. */
  96947. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  96948. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  96949. };
  96950. /**
  96951. * Standard reflectance value at parallel view angle.
  96952. */
  96953. BackgroundMaterial.StandardReflectance0 = 0.05;
  96954. /**
  96955. * Standard reflectance value at grazing angle.
  96956. */
  96957. BackgroundMaterial.StandardReflectance90 = 0.5;
  96958. __decorate([
  96959. BABYLON.serializeAsColor3()
  96960. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  96961. __decorate([
  96962. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  96963. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  96964. __decorate([
  96965. BABYLON.serializeAsColor3()
  96966. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  96967. __decorate([
  96968. BABYLON.serialize()
  96969. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  96970. __decorate([
  96971. BABYLON.serialize()
  96972. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  96973. __decorate([
  96974. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  96975. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  96976. __decorate([
  96977. BABYLON.serializeAsTexture()
  96978. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  96979. __decorate([
  96980. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96981. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  96982. __decorate([
  96983. BABYLON.serialize()
  96984. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  96985. __decorate([
  96986. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96987. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  96988. __decorate([
  96989. BABYLON.serializeAsTexture()
  96990. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  96991. __decorate([
  96992. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96993. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  96994. __decorate([
  96995. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  96996. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  96997. __decorate([
  96998. BABYLON.serialize()
  96999. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  97000. __decorate([
  97001. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97002. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  97003. __decorate([
  97004. BABYLON.serializeAsVector3()
  97005. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  97006. __decorate([
  97007. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97008. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  97009. __decorate([
  97010. BABYLON.serialize()
  97011. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  97012. __decorate([
  97013. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97014. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  97015. __decorate([
  97016. BABYLON.serialize()
  97017. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  97018. __decorate([
  97019. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97020. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  97021. __decorate([
  97022. BABYLON.serialize()
  97023. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  97024. __decorate([
  97025. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97026. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  97027. __decorate([
  97028. BABYLON.serialize()
  97029. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  97030. __decorate([
  97031. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97032. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  97033. __decorate([
  97034. BABYLON.serialize()
  97035. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  97036. __decorate([
  97037. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97038. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  97039. __decorate([
  97040. BABYLON.serialize()
  97041. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  97042. __decorate([
  97043. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97044. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  97045. __decorate([
  97046. BABYLON.serialize()
  97047. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  97048. __decorate([
  97049. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97050. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  97051. __decorate([
  97052. BABYLON.serialize()
  97053. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  97054. __decorate([
  97055. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97056. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  97057. __decorate([
  97058. BABYLON.serialize()
  97059. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  97060. __decorate([
  97061. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97062. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  97063. __decorate([
  97064. BABYLON.serializeAsImageProcessingConfiguration()
  97065. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  97066. return BackgroundMaterial;
  97067. }(BABYLON.PushMaterial));
  97068. BABYLON.BackgroundMaterial = BackgroundMaterial;
  97069. })(BABYLON || (BABYLON = {}));
  97070. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  97071. var __assign = (this && this.__assign) || Object.assign || function(t) {
  97072. for (var s, i = 1, n = arguments.length; i < n; i++) {
  97073. s = arguments[i];
  97074. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  97075. t[p] = s[p];
  97076. }
  97077. return t;
  97078. };
  97079. var BABYLON;
  97080. (function (BABYLON) {
  97081. /**
  97082. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  97083. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  97084. * It also helps with the default setup of your imageProcessing configuration.
  97085. */
  97086. var EnvironmentHelper = /** @class */ (function () {
  97087. /**
  97088. * constructor
  97089. * @param options
  97090. * @param scene The scene to add the material to
  97091. */
  97092. function EnvironmentHelper(options, scene) {
  97093. var _this = this;
  97094. this._errorHandler = function (message, exception) {
  97095. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  97096. };
  97097. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  97098. this._scene = scene;
  97099. this.onErrorObservable = new BABYLON.Observable();
  97100. this._setupBackground();
  97101. this._setupImageProcessing();
  97102. }
  97103. /**
  97104. * Creates the default options for the helper.
  97105. */
  97106. EnvironmentHelper._getDefaultOptions = function () {
  97107. return {
  97108. createGround: true,
  97109. groundSize: 15,
  97110. groundTexture: this._groundTextureCDNUrl,
  97111. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  97112. groundOpacity: 0.9,
  97113. enableGroundShadow: true,
  97114. groundShadowLevel: 0.5,
  97115. enableGroundMirror: false,
  97116. groundMirrorSizeRatio: 0.3,
  97117. groundMirrorBlurKernel: 64,
  97118. groundMirrorAmount: 1,
  97119. groundMirrorFresnelWeight: 1,
  97120. groundMirrorFallOffDistance: 0,
  97121. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  97122. groundYBias: 0.00001,
  97123. createSkybox: true,
  97124. skyboxSize: 20,
  97125. skyboxTexture: this._skyboxTextureCDNUrl,
  97126. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  97127. backgroundYRotation: 0,
  97128. sizeAuto: true,
  97129. rootPosition: BABYLON.Vector3.Zero(),
  97130. setupImageProcessing: true,
  97131. environmentTexture: this._environmentTextureCDNUrl,
  97132. cameraExposure: 0.8,
  97133. cameraContrast: 1.2,
  97134. toneMappingEnabled: true,
  97135. };
  97136. };
  97137. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  97138. /**
  97139. * Gets the root mesh created by the helper.
  97140. */
  97141. get: function () {
  97142. return this._rootMesh;
  97143. },
  97144. enumerable: true,
  97145. configurable: true
  97146. });
  97147. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  97148. /**
  97149. * Gets the skybox created by the helper.
  97150. */
  97151. get: function () {
  97152. return this._skybox;
  97153. },
  97154. enumerable: true,
  97155. configurable: true
  97156. });
  97157. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  97158. /**
  97159. * Gets the skybox texture created by the helper.
  97160. */
  97161. get: function () {
  97162. return this._skyboxTexture;
  97163. },
  97164. enumerable: true,
  97165. configurable: true
  97166. });
  97167. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  97168. /**
  97169. * Gets the skybox material created by the helper.
  97170. */
  97171. get: function () {
  97172. return this._skyboxMaterial;
  97173. },
  97174. enumerable: true,
  97175. configurable: true
  97176. });
  97177. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  97178. /**
  97179. * Gets the ground mesh created by the helper.
  97180. */
  97181. get: function () {
  97182. return this._ground;
  97183. },
  97184. enumerable: true,
  97185. configurable: true
  97186. });
  97187. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  97188. /**
  97189. * Gets the ground texture created by the helper.
  97190. */
  97191. get: function () {
  97192. return this._groundTexture;
  97193. },
  97194. enumerable: true,
  97195. configurable: true
  97196. });
  97197. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  97198. /**
  97199. * Gets the ground mirror created by the helper.
  97200. */
  97201. get: function () {
  97202. return this._groundMirror;
  97203. },
  97204. enumerable: true,
  97205. configurable: true
  97206. });
  97207. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  97208. /**
  97209. * Gets the ground mirror render list to helps pushing the meshes
  97210. * you wish in the ground reflection.
  97211. */
  97212. get: function () {
  97213. if (this._groundMirror) {
  97214. return this._groundMirror.renderList;
  97215. }
  97216. return null;
  97217. },
  97218. enumerable: true,
  97219. configurable: true
  97220. });
  97221. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  97222. /**
  97223. * Gets the ground material created by the helper.
  97224. */
  97225. get: function () {
  97226. return this._groundMaterial;
  97227. },
  97228. enumerable: true,
  97229. configurable: true
  97230. });
  97231. /**
  97232. * Updates the background according to the new options
  97233. * @param options
  97234. */
  97235. EnvironmentHelper.prototype.updateOptions = function (options) {
  97236. var newOptions = __assign({}, this._options, options);
  97237. if (this._ground && !newOptions.createGround) {
  97238. this._ground.dispose();
  97239. this._ground = null;
  97240. }
  97241. if (this._groundMaterial && !newOptions.createGround) {
  97242. this._groundMaterial.dispose();
  97243. this._groundMaterial = null;
  97244. }
  97245. if (this._groundTexture) {
  97246. if (this._options.groundTexture != newOptions.groundTexture) {
  97247. this._groundTexture.dispose();
  97248. this._groundTexture = null;
  97249. }
  97250. }
  97251. if (this._skybox && !newOptions.createSkybox) {
  97252. this._skybox.dispose();
  97253. this._skybox = null;
  97254. }
  97255. if (this._skyboxMaterial && !newOptions.createSkybox) {
  97256. this._skyboxMaterial.dispose();
  97257. this._skyboxMaterial = null;
  97258. }
  97259. if (this._skyboxTexture) {
  97260. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  97261. this._skyboxTexture.dispose();
  97262. this._skyboxTexture = null;
  97263. }
  97264. }
  97265. if (this._groundMirror && !newOptions.enableGroundMirror) {
  97266. this._groundMirror.dispose();
  97267. this._groundMirror = null;
  97268. }
  97269. if (this._scene.environmentTexture) {
  97270. if (this._options.environmentTexture != newOptions.environmentTexture) {
  97271. this._scene.environmentTexture.dispose();
  97272. }
  97273. }
  97274. this._options = newOptions;
  97275. this._setupBackground();
  97276. this._setupImageProcessing();
  97277. };
  97278. /**
  97279. * Sets the primary color of all the available elements.
  97280. * @param color the main color to affect to the ground and the background
  97281. */
  97282. EnvironmentHelper.prototype.setMainColor = function (color) {
  97283. if (this.groundMaterial) {
  97284. this.groundMaterial.primaryColor = color;
  97285. }
  97286. if (this.skyboxMaterial) {
  97287. this.skyboxMaterial.primaryColor = color;
  97288. }
  97289. if (this.groundMirror) {
  97290. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  97291. }
  97292. };
  97293. /**
  97294. * Setup the image processing according to the specified options.
  97295. */
  97296. EnvironmentHelper.prototype._setupImageProcessing = function () {
  97297. if (this._options.setupImageProcessing) {
  97298. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  97299. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  97300. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  97301. this._setupEnvironmentTexture();
  97302. }
  97303. };
  97304. /**
  97305. * Setup the environment texture according to the specified options.
  97306. */
  97307. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  97308. if (this._scene.environmentTexture) {
  97309. return;
  97310. }
  97311. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  97312. this._scene.environmentTexture = this._options.environmentTexture;
  97313. return;
  97314. }
  97315. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  97316. this._scene.environmentTexture = environmentTexture;
  97317. };
  97318. /**
  97319. * Setup the background according to the specified options.
  97320. */
  97321. EnvironmentHelper.prototype._setupBackground = function () {
  97322. if (!this._rootMesh) {
  97323. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  97324. }
  97325. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  97326. var sceneSize = this._getSceneSize();
  97327. if (this._options.createGround) {
  97328. this._setupGround(sceneSize);
  97329. this._setupGroundMaterial();
  97330. this._setupGroundDiffuseTexture();
  97331. if (this._options.enableGroundMirror) {
  97332. this._setupGroundMirrorTexture(sceneSize);
  97333. }
  97334. this._setupMirrorInGroundMaterial();
  97335. }
  97336. if (this._options.createSkybox) {
  97337. this._setupSkybox(sceneSize);
  97338. this._setupSkyboxMaterial();
  97339. this._setupSkyboxReflectionTexture();
  97340. }
  97341. this._rootMesh.position.x = sceneSize.rootPosition.x;
  97342. this._rootMesh.position.z = sceneSize.rootPosition.z;
  97343. this._rootMesh.position.y = sceneSize.rootPosition.y;
  97344. };
  97345. /**
  97346. * Get the scene sizes according to the setup.
  97347. */
  97348. EnvironmentHelper.prototype._getSceneSize = function () {
  97349. var _this = this;
  97350. var groundSize = this._options.groundSize;
  97351. var skyboxSize = this._options.skyboxSize;
  97352. var rootPosition = this._options.rootPosition;
  97353. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  97354. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  97355. }
  97356. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  97357. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  97358. });
  97359. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  97360. if (this._options.sizeAuto) {
  97361. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  97362. this._scene.activeCamera.upperRadiusLimit) {
  97363. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  97364. skyboxSize = groundSize;
  97365. }
  97366. var sceneDiagonalLenght = sceneDiagonal.length();
  97367. if (sceneDiagonalLenght > groundSize) {
  97368. groundSize = sceneDiagonalLenght * 2;
  97369. skyboxSize = groundSize;
  97370. }
  97371. // 10 % bigger.
  97372. groundSize *= 1.1;
  97373. skyboxSize *= 1.5;
  97374. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  97375. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  97376. }
  97377. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  97378. };
  97379. /**
  97380. * Setup the ground according to the specified options.
  97381. */
  97382. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  97383. var _this = this;
  97384. if (!this._ground) {
  97385. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  97386. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  97387. this._ground.parent = this._rootMesh;
  97388. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  97389. }
  97390. this._ground.receiveShadows = this._options.enableGroundShadow;
  97391. };
  97392. /**
  97393. * Setup the ground material according to the specified options.
  97394. */
  97395. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  97396. if (!this._groundMaterial) {
  97397. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  97398. }
  97399. this._groundMaterial.alpha = this._options.groundOpacity;
  97400. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  97401. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  97402. this._groundMaterial.primaryColor = this._options.groundColor;
  97403. this._groundMaterial.useRGBColor = false;
  97404. this._groundMaterial.enableNoise = true;
  97405. if (this._ground) {
  97406. this._ground.material = this._groundMaterial;
  97407. }
  97408. };
  97409. /**
  97410. * Setup the ground diffuse texture according to the specified options.
  97411. */
  97412. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  97413. if (!this._groundMaterial) {
  97414. return;
  97415. }
  97416. if (this._groundTexture) {
  97417. return;
  97418. }
  97419. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  97420. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  97421. return;
  97422. }
  97423. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  97424. diffuseTexture.gammaSpace = false;
  97425. diffuseTexture.hasAlpha = true;
  97426. this._groundMaterial.diffuseTexture = diffuseTexture;
  97427. };
  97428. /**
  97429. * Setup the ground mirror texture according to the specified options.
  97430. */
  97431. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  97432. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97433. if (!this._groundMirror) {
  97434. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  97435. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  97436. this._groundMirror.anisotropicFilteringLevel = 1;
  97437. this._groundMirror.wrapU = wrapping;
  97438. this._groundMirror.wrapV = wrapping;
  97439. this._groundMirror.gammaSpace = false;
  97440. if (this._groundMirror.renderList) {
  97441. for (var i = 0; i < this._scene.meshes.length; i++) {
  97442. var mesh = this._scene.meshes[i];
  97443. if (mesh !== this._ground &&
  97444. mesh !== this._skybox &&
  97445. mesh !== this._rootMesh) {
  97446. this._groundMirror.renderList.push(mesh);
  97447. }
  97448. }
  97449. }
  97450. }
  97451. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  97452. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  97453. };
  97454. /**
  97455. * Setup the ground to receive the mirror texture.
  97456. */
  97457. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  97458. if (this._groundMaterial) {
  97459. this._groundMaterial.reflectionTexture = this._groundMirror;
  97460. this._groundMaterial.reflectionFresnel = true;
  97461. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  97462. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  97463. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  97464. }
  97465. };
  97466. /**
  97467. * Setup the skybox according to the specified options.
  97468. */
  97469. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  97470. var _this = this;
  97471. if (!this._skybox) {
  97472. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  97473. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  97474. }
  97475. this._skybox.parent = this._rootMesh;
  97476. };
  97477. /**
  97478. * Setup the skybox material according to the specified options.
  97479. */
  97480. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  97481. if (!this._skybox) {
  97482. return;
  97483. }
  97484. if (!this._skyboxMaterial) {
  97485. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  97486. }
  97487. this._skyboxMaterial.useRGBColor = false;
  97488. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  97489. this._skyboxMaterial.enableNoise = true;
  97490. this._skybox.material = this._skyboxMaterial;
  97491. };
  97492. /**
  97493. * Setup the skybox reflection texture according to the specified options.
  97494. */
  97495. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  97496. if (!this._skyboxMaterial) {
  97497. return;
  97498. }
  97499. if (this._skyboxTexture) {
  97500. return;
  97501. }
  97502. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  97503. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  97504. return;
  97505. }
  97506. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  97507. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  97508. this._skyboxTexture.gammaSpace = false;
  97509. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  97510. };
  97511. /**
  97512. * Dispose all the elements created by the Helper.
  97513. */
  97514. EnvironmentHelper.prototype.dispose = function () {
  97515. if (this._groundMaterial) {
  97516. this._groundMaterial.dispose(true, true);
  97517. }
  97518. if (this._skyboxMaterial) {
  97519. this._skyboxMaterial.dispose(true, true);
  97520. }
  97521. this._rootMesh.dispose(false);
  97522. };
  97523. /**
  97524. * Default ground texture URL.
  97525. */
  97526. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  97527. /**
  97528. * Default skybox texture URL.
  97529. */
  97530. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  97531. /**
  97532. * Default environment texture URL.
  97533. */
  97534. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  97535. return EnvironmentHelper;
  97536. }());
  97537. BABYLON.EnvironmentHelper = EnvironmentHelper;
  97538. })(BABYLON || (BABYLON = {}));
  97539. //# sourceMappingURL=babylon.environmentHelper.js.map
  97540. var BABYLON;
  97541. (function (BABYLON) {
  97542. /**
  97543. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  97544. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  97545. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  97546. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  97547. */
  97548. var VideoDome = /** @class */ (function (_super) {
  97549. __extends(VideoDome, _super);
  97550. /**
  97551. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  97552. * @param name Element's name, child elements will append suffixes for their own names.
  97553. * @param urlsOrVideo
  97554. * @param options An object containing optional or exposed sub element properties:
  97555. * @param options **resolution=12** Integer, lower resolutions have more artifacts at extreme fovs
  97556. * @param options **clickToPlay=false** Add a click to play listener to the video, does not prevent autoplay.
  97557. * @param options **autoPlay=true** Automatically attempt to being playing the video.
  97558. * @param options **loop=true** Automatically loop video on end.
  97559. * @param options **size=1000** Physical radius to create the dome at, defaults to approximately half the far clip plane.
  97560. */
  97561. function VideoDome(name, urlsOrVideo, options, scene) {
  97562. var _this = _super.call(this, name, scene) || this;
  97563. // set defaults and manage values
  97564. name = name || "videoDome";
  97565. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  97566. options.clickToPlay = Boolean(options.clickToPlay);
  97567. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  97568. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  97569. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  97570. // create
  97571. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true };
  97572. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  97573. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  97574. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  97575. flat: false,
  97576. radius: options.size,
  97577. subdivisions: options.resolution,
  97578. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  97579. }, scene);
  97580. // configure material
  97581. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  97582. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  97583. material.reflectionTexture = _this._videoTexture;
  97584. material.useEquirectangularFOV = true;
  97585. material.fovMultiplier = 1.0;
  97586. // configure mesh
  97587. _this._mesh.material = material;
  97588. _this._mesh.parent = _this;
  97589. // optional configuration
  97590. if (options.clickToPlay) {
  97591. scene.onPointerUp = function () {
  97592. _this._videoTexture.video.play();
  97593. };
  97594. }
  97595. return _this;
  97596. }
  97597. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  97598. /**
  97599. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  97600. * Also see the options.resolution property.
  97601. */
  97602. get: function () {
  97603. return this._material.fovMultiplier;
  97604. },
  97605. set: function (value) {
  97606. this._material.fovMultiplier = value;
  97607. },
  97608. enumerable: true,
  97609. configurable: true
  97610. });
  97611. /**
  97612. * Releases resources associated with this node.
  97613. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  97614. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  97615. */
  97616. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  97617. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  97618. this._videoTexture.dispose();
  97619. this._mesh.dispose();
  97620. this._material.dispose();
  97621. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  97622. };
  97623. return VideoDome;
  97624. }(BABYLON.Node));
  97625. BABYLON.VideoDome = VideoDome;
  97626. })(BABYLON || (BABYLON = {}));
  97627. //# sourceMappingURL=babylon.videoDome.js.map
  97628. 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\nvec3 environmentRefraction=vec3(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).rgb;\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec3 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords).rgb;\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords).rgb,\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords).rgb,\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vec3(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).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance=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*=vReflectionInfos.x;\nenvironmentRadiance*=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*=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;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction;\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}","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 vec4 options;\nattribute float cellIndex;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec3 particlesInfos; \n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*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); \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 float size;\nin vec4 color;\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);\n\nvec4 viewPosition=view*vec4(position,1.0);\ngl_Position=projection*(viewPosition+vec4(offset*size,0.,0.));\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 color1;\nuniform vec4 color2;\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\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 angle;\nuniform float height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin float seed;\nin float size;\nin vec4 color;\nin vec3 direction;\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout float outSeed;\nout float outSize;\nout vec4 outColor;\nout vec3 outDirection;\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=0.;\noutDirection=direction;\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=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n\noutColor=color1+(color2-color1)*randoms.b;\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=PI*randoms2.y;\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius*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 (angle == 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;\noutDirection=(emitterWM*vec4(direction*power,0.)).xyz;\n} else { \noutPosition=position+direction*timeDelta;\noutAge=age+timeDelta;\noutLife=life;\noutSeed=seed;\noutColor=color;\noutSize=size;\noutDirection=direction+gravity*timeDelta;\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;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\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\nvec3 reflectionColor=vec3(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).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample.rgb;\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor=reflectionColor.bgr;\n#endif\n\nreflectionColor*=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*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,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"};
  97629. 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}","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};"};